import React from 'react';
import { cn } from '../../lib/utils';
import type { VariantProps } from 'class-variance-authority';
import { badgeVariants } from './badge-variants';
import { motion, AnimatePresence } from "framer-motion";
import {
  Check,
  CheckCircle2,
  AlertCircle,
  Code2,
  Plus,
  Trash2 as Trash,
  Copy,
  Terminal,
  ArrowLeft,
  Settings,
  Save,
  ExternalLink,
  Crown,
  Download,
  Bold,
  Italic,
  AlignRight,
  Eraser,
  ChevronUp,
  ChevronDown,
  Smile,
  Type,
  Underline,
  Strikethrough,
  AlignLeft,
  AlignCenter,
  ShieldCheck,
} from 'lucide-react';
import { Slot } from "radix-ui";
import { Switch } from './switch';
import { Badge } from './badge';
import { Input } from './input';
import { Label } from './label';
import { PhoneInput } from './PhoneInput';
import { toast } from "sonner";
import Editor from 'react-simple-code-editor';
import EmojiPicker, { EmojiStyle, Theme } from 'emoji-picker-react';
import { Popover, PopoverTrigger, PopoverContent } from './popover';
import NoticeBar from '../../NoticeBar';

// Fix for potentially problematic ESM import of Editor
const EditorComponent = (Editor as unknown as { default: React.ComponentType<Record<string, unknown>> }).default || Editor;

export { Badge };

export const SafeRender: React.FC<{ content: unknown, isHtml?: boolean }> = ({ content, isHtml = false }) => {
  if (content === null || content === undefined) return null;

  if (typeof content === 'string') {
    if (isHtml && (content.includes('<') || content.includes('&'))) return <span dangerouslySetInnerHTML={{ __html: content }} />;
    return <>{content}</>;
  }

  if (typeof content === 'number' || typeof content === 'boolean') {
    return <>{content.toString()}</>;
  }

  if (React.isValidElement(content)) {
    return content;
  }

  if (Array.isArray(content)) {
    return (
      <>
        {content.map((item, i) => (
          <SafeRender key={i} content={item} isHtml={isHtml} />
        ))}
      </>
    );
  }

  if (typeof content === 'object') {
    let str = '[Object]';
    try {
      str = JSON.stringify(content);
    } catch {
      str = '[Complex Object]';
    }
    return <span>{str}</span>;
  }

  return null;
};

export const StatusMessage: React.FC<{
  type: 'active' | 'inactive' | 'error' | 'warning',
  message: React.ReactNode,
  icon?: React.ComponentType<{ size?: number; className?: string }>,
  className?: string
}> = ({ type, message, icon: Icon, className = "" }) => {
  if (!message) return null;

  const styles = {
    active: { text: 'text-emerald-600', bg: 'bg-emerald-50/50', border: 'border-emerald-100', icon: CheckCircle2 },
    inactive: { text: 'text-slate-500', bg: 'bg-slate-50/50', border: 'border-slate-100', icon: AlertCircle },
    error: { text: 'text-rose-600', bg: 'bg-rose-50/50', border: 'border-rose-100', icon: AlertCircle },
    warning: { text: 'text-amber-600', bg: 'bg-amber-50/50', border: 'border-amber-100', icon: AlertCircle }
  };

  const style = styles[type];
  const DisplayIcon = Icon || style.icon;

  return (
    <motion.div
      initial={{ opacity: 0, y: -10 }}
      animate={{ opacity: 1, y: 0 }}
      className={`flex items-start gap-2.5 px-4 py-3 rounded-[5px] border ${style.bg} ${style.border} ${style.text} text-[13px] font-medium ${className}`}
    >
      <DisplayIcon size={16} className="shrink-0 mt-0.5" />
      <div>
        <SafeRender content={message} isHtml={true} />
      </div>
    </motion.div>
  );
};

export const SectionHeader: React.FC<{
  title: string;
  description?: string;
  className?: string;
  badge?: string;
  badgeColor?: 'blue' | 'brand' | 'emerald';
  icon?: React.ComponentType<{ size?: number; className?: string; opacity?: number; shrink?: number | string; strokeWidth?: number }>;
  rightAction?: React.ReactNode;
}> = ({ title, description = "", className = "", badge, badgeColor = 'brand', icon: Icon, rightAction }) => {
  const badgeStyles = {
    blue: 'bg-blue-50 text-blue-500 border-blue-100',
    brand: 'bg-[#004449]/10 text-[#004449] border-[#004449]/20',
    emerald: 'bg-emerald-50 text-emerald-500 border-emerald-100'
  };
  return (
    <div className={`flex flex-col md:flex-row md:items-center justify-between gap-4 ${className}`}>
      <div className="flex-1">
        <div className="text-lg font-bold flex items-center gap-2 text-slate-800">
          {Icon && <Icon className="w-5 h-5 opacity-70 shrink-0" />}
          <SafeRender content={title} />
          {badge && <span className={`text-[9px] font-black uppercase tracking-widest px-1.5 py-0.5 rounded border ${badgeStyles[badgeColor]}`}>{badge}</span>}
        </div>
        {description && <div className="text-xs font-medium text-slate-500 mt-1"><SafeRender content={description} /></div>}
      </div>
      {rightAction && <div>{rightAction}</div>}
    </div>
  );
};

export const SettingSwitchCard: React.FC<{
  label: string;
  description: string;
  checked: boolean;
  onChange: (checked: boolean) => void;
  disabled?: boolean;
  className?: string;
}> = ({ label, description, checked, onChange, disabled, className = "" }) => (
  <div className={`p-4 bg-slate-50 border border-slate-200 rounded-[5px] flex items-center justify-between group ${disabled ? 'opacity-60 cursor-not-allowed' : ''} ${className}`}>
    <div className="space-y-0.5 pr-4">
      <span className="block text-[13px] font-bold text-slate-900"><SafeRender content={label} /></span>
      <span className="block text-[10px] text-slate-400 font-bold uppercase tracking-tight leading-none"><SafeRender content={description} /></span>
    </div>
    <Switch
      checked={checked}
      onCheckedChange={onChange}
      disabled={disabled}
    />
  </div>
);

const RichInput = React.forwardRef<HTMLDivElement, {
  value: string;
  onChange: (val: string) => void;
  onBlur?: () => void;
  placeholder?: string;
  className?: string;
  hasIcon?: boolean;
}>(({ value, onChange, onBlur, placeholder, className, hasIcon }, ref) => {
  const innerRef = React.useRef<HTMLDivElement>(null);

  // Use a ref to combine with the forwarded ref
  React.useImperativeHandle(ref, () => innerRef.current!);

  // Sync internal state with prop
  React.useLayoutEffect(() => {
    if (innerRef.current) {
      const currentHTML = innerRef.current.innerHTML;
      const targetHTML = value || '';
      
      // Only update if they are truly different to prevent cursor jumps
      if (currentHTML !== targetHTML) {
        innerRef.current.innerHTML = targetHTML;
      }
    }
  }, [value]);

  const handleInput = () => {
    if (innerRef.current) {
      onChange(innerRef.current.innerHTML);
    }
  };

  return (
    <div className="relative w-full h-full">
      <div
        ref={innerRef}
        contentEditable
        onInput={handleInput}
        onBlur={onBlur}
        className={cn(
          "w-full h-full min-h-[40px] outline-none overflow-y-auto whitespace-pre-wrap break-words py-[11px]",
          className
        )}
      />
      {(!value || value === '<br>') && (
        <div className={cn(
          "absolute inset-0 flex items-center pointer-events-none text-slate-400/50 text-[13px] select-none",
          hasIcon ? "pl-10" : "pl-3.5"
        )}>
          {placeholder}
        </div>
      )}
    </div>
  );
});

RichInput.displayName = "RichInput";

export const SettingInput: React.FC<{
  label: string;
  value: string;
  onChange: (val: string) => void;
  onBlur?: () => void;
  placeholder?: string;
  type?: string;
  icon?: React.ComponentType<{ size?: number; className?: string; strokeWidth?: number }>;
  description?: string;
  button?: React.ReactNode;
  className?: string;
  labelHidden?: boolean;
  showFormatting?: boolean;
  showEmoji?: boolean;
  disabled?: boolean;
  onFormat?: (type: 'bold' | 'italic' | 'underline' | 'strike' | 'align-left' | 'align-center' | 'align-right' | 'clear' | 'size-up' | 'size-down' | 'color' | 'emoji', value?: string) => void;
}> = ({
  label,
  value,
  onChange,
  onBlur,
  placeholder,
  type = 'text',
  icon: Icon,
  description,
  button,
  className = "",
  labelHidden = false,
  showFormatting = false,
  showEmoji = false,
  disabled = false,
  onFormat
}) => {
    const inputRef = React.useRef<HTMLDivElement | HTMLInputElement>(null);
    const isRTL = typeof document !== 'undefined' && document.dir === 'rtl';

    const insertAtCursor = (text: string) => {
      if (!inputRef.current) return;

      if (showFormatting) {
        // ContentEditable insertion
        inputRef.current.focus();
        const selection = window.getSelection();
        if (selection && selection.rangeCount > 0) {
          const range = selection.getRangeAt(0);
          range.deleteContents();
          const node = document.createTextNode(text);
          range.insertNode(node);
          range.setStartAfter(node);
          range.setEndAfter(node);
          selection.removeAllRanges();
          selection.addRange(range);
          onChange(inputRef.current.innerHTML);
        } else {
          onChange(value + text);
        }
        return;
      }

      // Standard input insertion
      const input = inputRef.current as HTMLInputElement;
      const start = input?.selectionStart || 0;
      const end = input?.selectionEnd || 0;
      const newValue = value.substring(0, start) + text + value.substring(end);
      onChange(newValue);

      // Reset cursor position
      setTimeout(() => {
        if (inputRef.current) {
          const input = inputRef.current as HTMLInputElement;
          input.focus();
          input.setSelectionRange(start + text.length, start + text.length);
        }
      }, 10);
    };

    const handleFormatClick = (formatType: 'bold' | 'italic' | 'underline' | 'strike' | 'align-left' | 'align-center' | 'align-right' | 'clear' | 'size-up' | 'size-down' | 'color' | 'emoji', val?: string) => {
      if (formatType === 'emoji' && val) {
        insertAtCursor(val);
        return;
      }

      if (showFormatting) {
        document.execCommand('styleWithCSS', false, 'true');
        if (formatType === 'bold') document.execCommand('bold', false);
        if (formatType === 'italic') document.execCommand('italic', false);
        if (formatType === 'underline') document.execCommand('underline', false);
        if (formatType === 'strike') document.execCommand('strikeThrough', false);
        if (formatType === 'align-left') document.execCommand('justifyLeft', false);
        if (formatType === 'align-center') document.execCommand('justifyCenter', false);
        if (formatType === 'align-right') document.execCommand('justifyRight', false);
        if (formatType === 'clear') document.execCommand('removeFormat', false);

        if (formatType === 'size-up') {
          const selection = window.getSelection();
          if (selection && selection.rangeCount > 0) {
            const range = selection.getRangeAt(0);
            const span = document.createElement('span');
            span.style.fontSize = '1.2em';
            range.surroundContents(span);
          }
        }
        if (formatType === 'size-down') {
          const selection = window.getSelection();
          if (selection && selection.rangeCount > 0) {
            const range = selection.getRangeAt(0);
            const span = document.createElement('span');
            span.style.fontSize = '0.8em';
            range.surroundContents(span);
          }
        }

        if (inputRef.current) {
          onChange(inputRef.current.innerHTML);
        }
        return;
      }

      if (onFormat) {
        onFormat(formatType === 'emoji' ? 'color' : formatType, val);
        return;
      }

      // Default basic formatting logic for text inputs (when showFormatting is false but we have basic logic)
      const input = inputRef.current as HTMLInputElement;
      if (!input) return;
      const start = input.selectionStart || 0;
      const end = input.selectionEnd || 0;
      const selectedText = value.substring(start, end);

      let newValue = value;
      if (formatType === 'bold') {
        newValue = value.substring(0, start) + `<b>${selectedText}</b>` + value.substring(end);
      } else if (formatType === 'italic') {
        newValue = value.substring(0, start) + `<i>${selectedText}</i>` + value.substring(end);
      }

      if (newValue !== value) {
        onChange(newValue);
        setTimeout(() => {
          if (inputRef.current) {
            const input = inputRef.current as HTMLInputElement;
            input.focus();
            input.setSelectionRange(start, start + newValue.length - value.length + selectedText.length);
          }
        }, 10);
      }
    };

    return (
      <div className={`space-y-1.5 ${className}`}>
        <div className="flex items-center justify-between px-1">
          {!labelHidden && (
            <Label className="text-[10px] font-black text-slate-400 uppercase tracking-widest truncate block">
              <SafeRender content={label} />
            </Label>
          )}
        </div>

        <div className="relative group">
          {Icon && (
            <div className={cn(
              "absolute inset-y-0 flex items-center pointer-events-none text-slate-400 group-focus-within:text-[#004449] transition-colors z-20",
              isRTL ? "right-0 pr-3.5" : "left-0 pl-3.5"
            )}>
              <Icon size={16} />
            </div>
          )}
          {(showFormatting || showEmoji) ? (
            <RichInput

              ref={inputRef as React.Ref<HTMLDivElement>}
              value={value}
              onChange={onChange}
              onBlur={onBlur}
              placeholder={placeholder}
              hasIcon={!!Icon}
              className={cn(
                "flex-1 border-slate-200 bg-slate-50/30 focus:bg-white focus:border-[#004449] transition-all rounded-[5px] shadow-none text-[13px] border h-10 min-h-[40px]",
                Icon ? (isRTL ? '!pr-12' : '!pl-12') : (isRTL ? 'pr-3.5' : 'pl-3.5'),
                (showEmoji || showFormatting || button) ? (isRTL ? '!pl-20' : '!pr-20') : (isRTL ? 'pr-3.5' : 'pl-3.5'),
                className
              )}
            />
          ) : (
            <Input

              ref={inputRef as React.Ref<HTMLInputElement>}
              type={type}
              value={value}
              onChange={(e) => onChange(e.target.value)}
              onBlur={onBlur}
              disabled={disabled}
              className={cn(
                "h-10 border-slate-200 bg-slate-50/30 focus:bg-white focus:border-[#004449] transition-all rounded-[5px] shadow-none text-[13px]",
                Icon ? (isRTL ? '!pr-12' : '!pl-12') : (isRTL ? 'pr-3.5' : 'pl-3.5'),
                (showEmoji || showFormatting || button) ? (isRTL ? '!pl-20' : '!pr-20') : (isRTL ? 'pr-3.5' : 'pl-3.5'),
                disabled && "opacity-50 cursor-not-allowed",
                className
              )}
              placeholder={placeholder}
            />
          )}

          <div className="absolute right-1 top-1/2 -translate-y-1/2 flex items-center gap-0.5 z-20">
            {showFormatting && (
              <Popover>
                <PopoverTrigger asChild>
                  <button
                    type="button"
                    className="p-1.5 text-slate-300 hover:text-[#004449] transition-colors bg-transparent border-none cursor-pointer rounded-full hover:bg-slate-100"
                    title="Text Styles"
                  >
                    <Type size={16} />
                  </button>
                </PopoverTrigger>
                <PopoverContent className="w-48 p-2 z-[1002] bg-white border border-slate-200 shadow-2xl rounded-xl" align="end" side="top" sideOffset={8}>
                  <div className="space-y-1">
                    <div className="px-2 py-1.5 mb-1 border-b border-slate-50">
                      <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Formatting</span>
                    </div>
                    <div className="grid grid-cols-4 gap-1 p-1 bg-slate-50 rounded-lg mb-2">
                      <button onClick={() => handleFormatClick('bold')} className="p-2 hover:bg-white rounded shadow-sm transition-all flex items-center justify-center text-slate-600 hover:text-[#004449]" title="Bold"><Bold size={14} /></button>
                      <button onClick={() => handleFormatClick('italic')} className="p-2 hover:bg-white rounded shadow-sm transition-all flex items-center justify-center text-slate-600 hover:text-[#004449]" title="Italic"><Italic size={14} /></button>
                      <button onClick={() => handleFormatClick('underline')} className="p-2 hover:bg-white rounded shadow-sm transition-all flex items-center justify-center text-slate-600 hover:text-[#004449]" title="Underline"><Underline size={14} /></button>
                      <button onClick={() => handleFormatClick('strike')} className="p-2 hover:bg-white rounded shadow-sm transition-all flex items-center justify-center text-slate-600 hover:text-[#004449]" title="Strikethrough"><Strikethrough size={14} /></button>
                    </div>

                    <div className="grid grid-cols-3 gap-1 p-1 bg-slate-50 rounded-lg mb-2">
                      <button onClick={() => handleFormatClick('align-left')} className="p-2 hover:bg-white rounded shadow-sm transition-all flex items-center justify-center text-slate-600 hover:text-[#004449]" title="Align Left"><AlignLeft size={14} /></button>
                      <button onClick={() => handleFormatClick('align-center')} className="p-2 hover:bg-white rounded shadow-sm transition-all flex items-center justify-center text-slate-600 hover:text-[#004449]" title="Align Center"><AlignCenter size={14} /></button>
                      <button onClick={() => handleFormatClick('align-right')} className="p-2 hover:bg-white rounded shadow-sm transition-all flex items-center justify-center text-slate-600 hover:text-[#004449]" title="Align Right"><AlignRight size={14} /></button>
                    </div>

                    <div className="h-[1px] bg-slate-100 my-2" />

                    <button
                      onClick={() => handleFormatClick('size-up')}
                      className="w-full flex items-center justify-between px-2.5 py-2 hover:bg-slate-50 rounded-lg transition-all text-left group"
                    >
                      <span className="text-sm text-slate-700 font-medium" style={{ fontSize: '15px' }}>Increase Size</span>
                      <ChevronUp size={12} className="text-slate-300 group-hover:text-[#004449]" />
                    </button>
                    <button
                      onClick={() => handleFormatClick('size-down')}
                      className="w-full flex items-center justify-between px-2.5 py-2 hover:bg-slate-50 rounded-lg transition-all text-left group"
                    >
                      <span className="text-sm text-slate-700 font-medium" style={{ fontSize: '11px' }}>Decrease Size</span>
                      <ChevronDown size={12} className="text-slate-300 group-hover:text-[#004449]" />
                    </button>

                    <div className="h-[1px] bg-slate-100 my-2" />

                    <button
                      onClick={() => handleFormatClick('clear')}
                      className="w-full flex items-center justify-between px-2.5 py-2 hover:bg-rose-50 rounded-lg transition-all text-left group"
                    >
                      <span className="text-[12px] text-rose-600 font-bold flex items-center gap-2">
                        <Eraser size={12} />
                        Clear All
                      </span>
                    </button>
                  </div>
                </PopoverContent>
              </Popover>
            )}
            {showEmoji && (
              <Popover>
                <PopoverTrigger asChild>
                  <button
                    type="button"
                    className="p-1.5 text-slate-300 hover:text-amber-500 transition-colors bg-transparent border-none cursor-pointer rounded-full hover:bg-slate-100"
                    title="Add Emoji"
                  >
                    <Smile size={16} />
                  </button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0 z-[101] border-none shadow-2xl rounded-xl" align="end" side="top" sideOffset={8}>
                  <EmojiPicker
                    onEmojiClick={(emojiData: { emoji: string }) => handleFormatClick('emoji', emojiData.emoji)}
                    autoFocusSearch={true}
                    theme={Theme.LIGHT}
                    emojiStyle={EmojiStyle.APPLE}
                    searchPlaceholder="Search emojis..."
                    width={300}
                    height={350}
                    skinTonesDisabled={false}
                    previewConfig={{ showPreview: false }}
                  />
                </PopoverContent>
              </Popover>
            )}
            {button}
          </div>
        </div>
        {description && <p className="text-[10px] text-slate-400 font-bold px-1 m-0"><SafeRender content={description} /></p>}
      </div>
    );
  };

export const SettingPhoneInput: React.FC<{
  label: string;
  value: string;
  onChange: (val: string) => void;
  description?: string;
  className?: string;
  defaultCountry?: import('libphonenumber-js').CountryCode;
}> = ({ label, value, onChange, description, className = "", defaultCountry }) => (
  <div className={`space-y-1.5 ${className}`}>
    <Label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 truncate block"><SafeRender content={label} /></Label>
    <PhoneInput
      value={value}
      onChange={onChange}
      defaultCountry={defaultCountry}
      className="h-10"
      inputClassName="h-10 border-slate-200 bg-slate-50/30 focus:bg-white focus:border-[#004449] transition-all rounded-lg shadow-none text-[13px]"
    />
    {description && <p className="text-[10px] text-slate-400 font-bold px-1 m-0"><SafeRender content={description} /></p>}
  </div>
);

export const MethodButton: React.FC<{
  active: boolean;
  label: string;
  description?: string;
  icon?: React.ComponentType<{ size?: number; className?: string; strokeWidth?: number }>;
  iconPath?: string;
  onClick: () => void;
  color?: string;
  bg?: string;
  activeStyles?: string;
  disabled?: boolean;
  className?: string;
}> = ({
  active,
  label,
  description,
  icon: Icon,
  iconPath,
  onClick,
  color = "text-indigo-600",
  bg = "bg-indigo-50",
  activeStyles = "bg-white border-[#004449] ring-4 ring-[#004449]/5",
  disabled = false,
  className = ""
}) => {
    const isRTL = typeof document !== 'undefined' && document.dir === 'rtl';

    return (
      <div className={cn("relative group", className)}>
        <label className={cn(
          "flex items-center gap-3 p-3 rounded-xl border-2 transition-all cursor-pointer relative overflow-hidden",
          active
            ? activeStyles
            : "bg-white border-slate-100 hover:border-slate-200",
          disabled && "opacity-50 cursor-not-allowed grayscale pointer-events-none"
        )}>
          <input
            type="radio"
            checked={active}
            onChange={onClick}
            className="sr-only"
            disabled={disabled}
          />

          <div className={cn(
            "w-10 h-10 rounded-lg flex items-center justify-center transition-all border duration-300 shrink-0",
            active ? `${bg} border-current/10` : "bg-slate-50 border-slate-100"
          )}>
            {iconPath ? (
              <img src={iconPath} className="w-5 h-5 object-contain" alt="" />
            ) : Icon && (
              <Icon size={18} className={cn("transition-colors", active ? color : "text-slate-400")} />
            )}
          </div>

          <div className={cn("flex-1 min-w-0 flex flex-col justify-center", isRTL ? "text-right" : "text-left")}>
            <h4 className={cn(
              "text-[14px] font-bold tracking-tight !m-0 !p-0 leading-tight",
              active ? "text-slate-900" : "text-slate-700"
            )}>{label}</h4>
            {description && <p className="text-[11px] font-medium text-slate-400 truncate !m-0 !p-0 leading-tight mt-0.5">{description}</p>}
          </div>

          <div className={cn(
            "w-5 h-5 rounded-full border-2 flex items-center justify-center transition-all shrink-0",
            active
              ? "bg-[#004449] border-[#004449] text-white"
              : "border-slate-200 shadow-inner bg-slate-50"
          )}>
            {active && <ShieldCheck size={12} strokeWidth={3} />}
          </div>
        </label>
      </div>
    );
  };

export const ColorInput: React.FC<{
  label: string;
  value: string;
  onChange: (val: string) => void;
}> = ({ label, value, onChange }) => (
  <div className="space-y-1.5">
    <label className="text-[9px] font-black text-slate-400 uppercase tracking-widest px-1 truncate block">{label}</label>
    <div className="flex items-center gap-2 p-1.5 bg-white border border-slate-200 rounded-[5px]">
      <input
        type="color"
        value={value || '#000000'}
        onChange={(e) => onChange(e.target.value)}
        className="h-7 w-7 shrink-0 rounded border-0 overflow-hidden cursor-pointer shadow-none"
      />
      <input
        type="text"
        value={value || ''}
        onChange={(e) => onChange(e.target.value)}
        className="w-full text-[11px] font-mono font-bold uppercase outline-none text-slate-600"
      />
    </div>
  </div>
);

export const CodeEditor: React.FC<{
  value: string;
  onChange: (val: string) => void;
  label?: string;
  placeholder?: string;
  language?: string;
}> = ({ value = "", onChange, label = "Custom CSS", placeholder = ".class { \n  color: red; \n}", language = "css" }) => {
  const lineCount = (value || "").split('\n').length;
  const isEditing = value.trim().length > 0;

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between px-1">
        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest"><SafeRender content={label} /></label>
        <div className="flex items-center gap-2">
          <span className="text-[9px] font-black text-[#004449] uppercase tracking-widest bg-[#004449]/5 px-2 py-0.5 rounded border border-[#004449]/10">{language}</span>
          <button
            onClick={() => {
              navigator.clipboard.writeText(value);
              toast.success("Code copied to clipboard");
            }}
            className="p-1.5 text-slate-400 hover:text-slate-900 transition-colors"
            title="Copy Code"
          >
            <Copy size={14} />
          </button>
        </div>
      </div>

      <div className="relative rounded-[5px] border border-slate-200 bg-slate-900 overflow-hidden group transition-all focus-within:ring-2 focus-within:ring-[#004449]/20 focus-within:border-[#004449]/50">
        {/* Line Numbers Sidebar */}
        <div className="absolute top-0 left-0 w-12 h-full bg-slate-900 border-r border-white/5 flex flex-col items-center pt-4 select-none pointer-events-none z-10">
          {Array.from({ length: Math.max(lineCount, 15) }).map((_, i) => (
            <span key={i} className="text-[10px] font-mono text-slate-600 leading-[21px] h-[21px]">{i + 1}</span>
          ))}
        </div>

        <div className="w-full min-h-[350px] pl-12 bg-slate-900 editor-container">
          <EditorComponent
            value={value}
            onValueChange={onChange}
            highlight={(code: string) => {
              const p = window.Prism;
              if (!p || !p.languages.css) return code;
              return p.highlight(code, p.languages.css, 'css');
            }}
            padding={16}
            placeholder={placeholder}
            className="font-mono text-[13px] leading-[21px] min-h-[350px] outline-none text-slate-300"
            style={{
              fontFamily: '"Fira Code", "Fira Mono", monospace',
              backgroundColor: 'transparent',
              counterReset: 'line',
            }}
          />
        </div>

        <div className="absolute bottom-3 right-4 flex items-center gap-2 pointer-events-none bg-slate-900/80 backdrop-blur px-2 py-1 rounded-lg border border-white/5 opacity-0 group-hover:opacity-100 transition-opacity z-20">
          <Terminal size={12} className="text-slate-500" />
          <span className="text-[9px] font-mono text-slate-500 uppercase tracking-tighter">{lineCount} lines</span>
        </div>
      </div>

      <div className={`flex items-start gap-2.5 p-4 border rounded-[5px] transition-all duration-500 ${isEditing ? 'bg-emerald-50/50 border-emerald-100 text-emerald-600' : 'bg-blue-50/50 border-blue-100 text-blue-600'}`}>
        <div className={`h-5 w-5 rounded-full flex items-center justify-center shrink-0 ${isEditing ? 'bg-emerald-100' : 'bg-blue-100'}`}>
          {isEditing ? <Check size={12} /> : <AlertCircle size={12} />}
        </div>
        <div>
          <p className="text-[12px] font-bold leading-none mb-1">{isEditing ? 'Custom Styles Active' : 'Standard design is active'}</p>
          <p className={`text-[11px] font-medium leading-relaxed opacity-80`}>
            {isEditing
              ? 'Your custom styles are being applied with high priority to the registration form.'
              : 'Your custom styles will be injected into the footer and applied with high priority to override default layouts.'
            }
          </p>
        </div>
      </div>
    </div>
  );
};

export const IntegrationCard: React.FC<{
  title: string;
  description: string;
  code: string;
  badge: string;
  badgeColor?: 'blue' | 'brand' | 'emerald';
  icon: React.ComponentType<{ size?: number; className?: string; opacity?: number; shrink?: number | string }>;
  variant?: 'light' | 'brand';
}> = ({ title, description, code, badge, badgeColor = 'blue', icon: Icon }) => {
  const badgeStyles = {
    blue: 'bg-blue-50 text-blue-600 border-blue-100',
    brand: 'bg-[#004449]/10 text-[#004449] border-[#004449]/20',
    emerald: 'bg-emerald-50 text-emerald-600 border-emerald-100'
  };

  return (
    <SettingCard className="p-0 overflow-hidden bg-white group hover:border-[#004449]/20 transition-all">
      <ModernCardHeader
        title={title}
        description={description}
        icon={Icon}
        rightAction={
          <div className="flex items-center gap-3">
            <span className={`text-[9px] font-black uppercase tracking-widest border px-2 py-0.5 rounded-full ${badgeStyles[badgeColor]}`}>{badge}</span>
            <button
              onClick={() => {
                navigator.clipboard.writeText(code);
                toast.success(`${title} copied!`);
              }}
              className="h-9 w-9 bg-white hover:bg-slate-50 text-slate-400 hover:text-slate-900 border border-slate-200 rounded-[5px] flex items-center justify-center transition-all active:scale-90 shadow-sm"
            >
              <Copy size={16} />
            </button>
          </div>
        }
      />

      <div className="p-6 md:p-8">
        <div className="relative rounded-[5px] border font-mono text-[12px] overflow-hidden bg-slate-50/50 border-slate-100">
          <div className="p-4 text-slate-700">
            {code}
          </div>
          <div className="absolute top-0 right-0 h-full w-1 bg-[#004449]/20"></div>
        </div>
      </div>
    </SettingCard>
  );
};

export const ShortcodeManager: React.FC<{
  shortcodes: string[];
  onChange: (newShortcodes: string[]) => void;
  title: string;
  description: string;
  placeholder?: string;
  systemShortcode?: string;
}> = ({ shortcodes, onChange, title, description, placeholder = "[your_shortcode]", systemShortcode }) => {
  const add = () => onChange([...shortcodes, ""]);
  const remove = (index: number) => onChange(shortcodes.filter((_, i) => i !== index));
  const update = (index: number, val: string) => {
    const next = [...shortcodes];
    next[index] = val;
    onChange(next);
  };

  return (
    <SettingCard className="p-0 overflow-hidden group hover:border-[#004449]/20 transition-all">
      <ModernCardHeader
        title={title}
        description={description}
        icon={Code2}
        rightAction={
          <PrimaryButton
            onClick={add}
            icon={Plus}
            className="h-10 px-6"
          >
            Add Extension
          </PrimaryButton>
        }
      />

      <div className="p-6 md:p-8 space-y-4">
        {systemShortcode && (
          <div className="p-5 bg-[#004449]/5 border border-[#004449]/10 rounded-[5px] flex items-center justify-between group/sc transition-all hover:bg-[#004449]/10">
            <div className="flex items-center gap-4">
              <div className="h-10 w-10 border border-[#004449]/10 rounded-[5px] bg-white flex items-center justify-center text-[#004449]">
                <Code2 size={18} />
              </div>
              <div>
                <code className="text-[13px] font-mono font-black text-[#004449] tracking-tight">{systemShortcode}</code>
                <p className="text-[10px] text-[#004449]/60 font-bold uppercase tracking-tight m-0">Primary Registration Shortcode</p>
              </div>
            </div>
            <span className="text-[9px] font-black text-[#004449]/60 border border-[#004449]/20 px-2 py-0.5 rounded-full bg-white shadow-sm">Default</span>
          </div>
        )}

        <AnimatePresence>
          {shortcodes.map((sc, idx) => (
            <motion.div
              key={idx}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="relative group/box bg-slate-50/50 border border-slate-100 rounded-[5px] p-1 transition-all hover:border-slate-200 hover:bg-white"
            >
              <div className="absolute inset-y-0 left-4 flex items-center pointer-events-none text-slate-400 group-focus-within/box:text-[#004449] transition-colors">
                <Terminal size={14} />
              </div>
              <input
                value={sc}
                onChange={(e) => update(idx, e.target.value)}
                className="w-full pl-12 pr-14 h-11 bg-transparent border-0 focus:ring-0 outline-none font-mono text-[13px] font-bold text-slate-700"
                placeholder={placeholder}
              />
              <button
                onClick={() => remove(idx)}
                className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 flex items-center justify-center text-rose-300 hover:text-rose-500 hover:bg-rose-50 rounded-[5px] transition-all active:scale-90"
              >
                <Trash size={16} />
              </button>
            </motion.div>
          ))}
        </AnimatePresence>

        {shortcodes.length === 0 && !systemShortcode && (
          <div className="py-16 text-center bg-slate-50/30 border-2 border-dashed border-slate-200 rounded-[5px]">
            <div className="h-12 w-12 rounded-full bg-white border border-slate-100 flex items-center justify-center mx-auto mb-4 text-slate-300 shadow-sm">
              <Code2 size={24} />
            </div>
            <h5 className="text-[13px] font-bold text-slate-500 mb-1">No extensions defined</h5>
            <p className="text-slate-400 text-[11px]">Use custom shortcodes to inject content before or after the form.</p>
          </div>
        )}
      </div>
    </SettingCard>
  );
};


export const BannerCard: React.FC<{
  title: string;
  description?: React.ReactNode;
  badge: string;
  color: 'emerald' | 'blue' | 'orange';
  icon?: React.ComponentType<{ size?: number; className?: string; opacity?: number; shrink?: number | string; strokeWidth?: number }>;
  iconPath?: string;
  children?: React.ReactNode;
}> = ({ title, description, badge, color, icon: Icon, iconPath, children }) => {
  const styles = {
    emerald: { badgeText: 'text-emerald-600 border-emerald-200 bg-emerald-50' },
    blue: { badgeText: 'text-blue-600 border-blue-200 bg-blue-50' },
    orange: { badgeText: 'text-orange-600 border-orange-200 bg-orange-50' }
  };
  const s = styles[color];
  return (
    <SettingCard className={`p-0 overflow-hidden group hover:border-${color}-200 transition-all shadow-none`}>
      <ModernCardHeader
        title={title}
        description={description}
        icon={Icon}
        iconPath={iconPath}
        rightAction={
          <span className={`text-[10px] font-black uppercase tracking-widest px-2.5 py-1 border rounded-full ${s.badgeText}`}>{badge}</span>
        }
      />
      <div className="p-6 md:p-8">
        {children}
      </div>
    </SettingCard>
  );
};
export const FlatTabs: React.FC<{
  tabs: { id: string; label: string; icon: React.ComponentType<{ size?: number; className?: string }> }[];
  activeTab: string;
  onTabChange: (id: string) => void;
  className?: string;
}> = ({ tabs, activeTab, onTabChange, className = "" }) => (
  <div className={`bg-white border border-[#dcdcde] p-1 inline-flex rounded-[5px] overflow-x-auto max-w-full no-scrollbar mb-6 ${className}`}>
    {tabs.map(tab => (
      <button
        key={tab.id}
        onClick={() => onTabChange(tab.id)}
        className={`px-5 py-2 text-[12px] font-semibold rounded-[4px] transition-all flex items-center gap-2 whitespace-nowrap ${activeTab === tab.id
          ? 'bg-[#004449]/10 text-[#004449]'
          : 'text-gray-500 hover:text-gray-700'
          }`}
      >
        <tab.icon size={14} />
        {tab.label}
      </button>
    ))}
  </div>
);

export { Tabs, TabsList, TabsTrigger, TabsContent } from './tabs';

export const PageHeader: React.FC<{
  title: React.ReactNode;
  description: React.ReactNode;
}> = ({ title, description }) => (
  <div className="text-left">
    <h1 className="text-[17px] font-semibold tracking-tight text-gray-900 leading-tight"><SafeRender content={title} /></h1>
    <p className="text-[12px] text-gray-500 mt-1 font-medium"><SafeRender content={description} /></p>
  </div>
);

export const SettingsLayout: React.FC<{
  children: React.ReactNode;
  className?: string;
  style?: React.CSSProperties;
  id?: string;
  dir?: 'ltr' | 'rtl';
  maxWidth?: string;
  noPadding?: boolean;
}> = ({ children, className = "", style, id, dir, maxWidth = "max-w-7xl", noPadding = false }) => (
  <div
    id={id}
    dir={dir}
    className={className}
    style={style}
  >
    <div className={cn(
      "flex-1",
      noPadding ? maxWidth : `mx-auto px-4 md:px-10 py-2 md:py-8 space-y-4 md:space-y-6 animate-in fade-in duration-500 ${maxWidth}`
    )}>
      {children}
    </div>
  </div>
);



export const SettingsHeader: React.FC<{
  title: string;
  description: string;
  backUrl?: string;
  onBack?: () => void;
  children?: React.ReactNode;
  className?: string;
}> = ({ title, description, backUrl, onBack, children, className = "" }) => (
  <div className={`space-y-6 mb-6 ${className}`}>
    <NoticeBar />
    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
      <div className="flex items-start gap-3">
        {onBack ? (
          <button
            onClick={onBack}
            className="sm:hidden flex items-center justify-center w-8 h-8 bg-white border border-[#dcdcde] rounded-lg hover:bg-gray-50 transition-all shadow-none group shrink-0 mt-1"
            title="Back"
          >
            <ArrowLeft className="w-4 h-4 text-gray-500 group-hover:text-gray-900 transition-colors" />
          </button>
        ) : backUrl ? (
          <a
            href={backUrl}
            className="sm:hidden flex items-center justify-center w-8 h-8 bg-white border border-[#dcdcde] rounded-lg hover:bg-gray-50 transition-all shadow-none group shrink-0 mt-1"
            title="Back"
          >
            <ArrowLeft className="w-4 h-4 text-gray-500 group-hover:text-gray-900 transition-colors" />
          </a>
        ) : null}
        <PageHeader title={title} description={description} />
      </div>

      <div className="flex flex-wrap items-center gap-2.5">
        {onBack ? (
          <button
            onClick={onBack}
            className="max-sm:hidden flex items-center justify-center w-8 h-8 bg-white border border-[#dcdcde] rounded-lg hover:bg-gray-50 transition-all shadow-none group shrink-0"
            title="Back"
          >
            <ArrowLeft className="w-4 h-4 text-gray-500 group-hover:text-gray-900 transition-colors" />
          </button>
        ) : backUrl ? (
          <a
            href={backUrl}
            className="max-sm:hidden flex items-center justify-center w-8 h-8 bg-white border border-[#dcdcde] rounded-lg hover:bg-gray-50 transition-all shadow-none group shrink-0"
            title="Back"
          >
            <ArrowLeft className="w-4 h-4 text-gray-500 group-hover:text-gray-900 transition-colors" />
          </a>
        ) : null}
        {children}
      </div>
    </div>
  </div>
);

// --- Standardized Button Components (from User Snippets) ---

export const AdminButton: React.FC<{
  children?: React.ReactNode;
  onClick?: (e?: React.MouseEvent) => void;
  disabled?: boolean;
  className?: string;
  icon?: React.ComponentType<{ size?: number; className?: string; strokeWidth?: number }>;
  loading?: boolean;
  size?: 'sm' | 'md' | 'lg' | 'icon' | 'icon-sm' | 'default';
  asChild?: boolean;
  type?: 'button' | 'submit' | 'reset';
  title?: string;
}> = ({ children, onClick, disabled, className = "", icon: Icon, loading, size = 'default', asChild = false, ...props }) => {
  const Comp = (asChild ? Slot : "button") as React.ElementType;
  const sizeClasses = {
    sm: 'h-8 px-3 text-[12px]',
    md: 'h-9 px-4 text-[13px]',
    lg: 'h-10 px-6 text-[14px]',
    icon: 'w-9 h-9 p-0',
    'icon-sm': 'w-8 h-8 p-0',
    default: 'h-8 px-3 text-[12px]'
  };
  return (
    <Comp
      onClick={onClick}
      disabled={disabled || loading}
      className={`inline-flex items-center justify-center whitespace-nowrap rounded-lg border border-transparent bg-[#004449] !text-white hover:bg-[#003337] transition-all disabled:pointer-events-none disabled:opacity-50 outline-none select-none cursor-pointer gap-1.5 active:scale-95 font-bold ${sizeClasses[size]} ${className}`}
      {...props}
    >
      {!asChild && (loading ? <div className="w-3 h-3 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : Icon && <Icon size={16} className="mr-0.5" />)}
      {children}
    </Comp>
  );
};

export const SecondaryButton: React.FC<{
  children?: React.ReactNode;
  onClick?: (e?: React.MouseEvent) => void;
  disabled?: boolean;
  className?: string;
  icon?: React.ComponentType<{ size?: number; className?: string; strokeWidth?: number }>;
  loading?: boolean;
  size?: 'sm' | 'md' | 'lg' | 'icon' | 'icon-sm' | 'default';
  asChild?: boolean;
  type?: 'button' | 'submit' | 'reset';
  title?: string;
}> = ({ children, onClick, disabled, className = "", icon: Icon, loading, size = 'default', asChild = false, ...props }) => {
  const Comp = (asChild ? Slot : "button") as React.ElementType;
  const sizeClasses = {
    sm: 'h-8 px-3 text-[12px]',
    md: 'h-9 px-4 text-[13px]',
    lg: 'h-10 px-6 text-[14px]',
    icon: 'w-9 h-9 p-0',
    'icon-sm': 'w-8 h-8 p-0',
    default: 'h-8 px-3 text-[12px]'
  };
  return (
    <Comp
      onClick={onClick}
      disabled={disabled || loading}
      className={`inline-flex items-center justify-center whitespace-nowrap rounded-lg border border-[#dcdcde] bg-white text-gray-700 hover:bg-gray-50 transition-all disabled:pointer-events-none disabled:opacity-50 outline-none select-none cursor-pointer font-medium gap-1.5 active:scale-95 ${sizeClasses[size]} ${className}`}
      {...props}
    >
      {!asChild && (loading ? <div className="w-3 h-3 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin" /> : Icon && <Icon size={14} className="text-gray-400 mr-0.5" />)}
      {children}
    </Comp>
  );
};

export const GhostButton: React.FC<{
  children?: React.ReactNode;
  onClick?: (e?: React.MouseEvent) => void;
  disabled?: boolean;
  className?: string;
  icon?: React.ComponentType<{ size?: number; className?: string; strokeWidth?: number }>;
  loading?: boolean;
  size?: 'sm' | 'md' | 'lg' | 'icon' | 'icon-sm' | 'default';
  asChild?: boolean;
  type?: 'button' | 'submit' | 'reset';
  title?: string;
}> = ({ children, onClick, disabled, className = "", icon: Icon, loading, size = 'default', asChild = false, ...props }) => {
  const Comp = (asChild ? Slot : "button") as React.ElementType;
  const sizeClasses = {
    sm: 'h-8 px-3 text-[12px]',
    md: 'h-9 px-4 text-[13px]',
    lg: 'h-10 px-6 text-[14px]',
    icon: 'w-9 h-9 p-0',
    'icon-sm': 'w-8 h-8 p-0',
    default: 'h-8 px-3 text-[12px]'
  };
  return (
    <Comp
      onClick={onClick}
      disabled={disabled || loading}
      className={`inline-flex items-center justify-center whitespace-nowrap rounded-md transition-all hover:bg-slate-50 text-slate-400 hover:text-slate-900 border border-transparent select-none cursor-pointer outline-none active:scale-95 ${sizeClasses[size]} ${className}`}
      {...props}
    >
      {!asChild && (loading ? <div className="w-3 h-3 border-2 border-slate-300 border-t-slate-600 rounded-full animate-spin" /> : Icon && <Icon size={16} />)}
      {children}
    </Comp>
  );
};

export const SuccessButton: React.FC<{
  children: React.ReactNode;
  onClick?: (e?: React.MouseEvent) => void;
  disabled?: boolean;
  className?: string;
  icon?: React.ComponentType<{ size?: number; className?: string; strokeWidth?: number }>;
  loading?: boolean;
  size?: 'sm' | 'md' | 'lg' | 'default';
}> = ({ children, onClick, disabled, className = "", icon: Icon, loading, size = 'default' }) => {
  const sizeClasses = {
    sm: 'h-8 px-3 text-[12px]',
    md: 'h-9 px-4 text-[13px]',
    lg: 'h-10 px-6 text-[14px]',
    icon: 'w-9 h-9 p-0',
    'icon-sm': 'w-8 h-8 p-0',
    default: 'h-8 px-3 text-[12px]'
  };
  return (
    <button
      onClick={onClick}
      disabled={disabled || loading}
      className={`inline-flex items-center justify-center whitespace-nowrap rounded-md font-semibold transition-all hover:scale-[1.02] active:scale-[0.98] border border-transparent select-none cursor-pointer outline-none gap-1.5 ${sizeClasses[size]} ${className.includes('bg-') ? className : 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-emerald-600/20'} ${className}`}
    >
      {loading ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : Icon && <Icon size={16} />}
      {children}
    </button>
  );
};

// Aliases for compatibility
export const PrimaryButton = AdminButton;
export const OutlineButton = SecondaryButton;

export const SettingCard: React.FC<{
  children: React.ReactNode;
  className?: string;
  dir?: 'ltr' | 'rtl';
}> = ({ children, className = "", dir }) => (
  <div dir={dir} className={`p-0 bg-white border border-[#dcdcde] rounded-[5px] shadow-none overflow-hidden ${className}`}>
    {children}
  </div>
);

export const SnapshotStat: React.FC<{
  value: string;
  label: string;
  sub: string;
  badge: string;
  badgeVariant?: 'secondary' | 'green' | 'yellow' | 'blue' | 'gray' | 'success' | 'warning' | 'outline';
  percent: string | number;
  barColor: string;
  valueClass?: string;
  percentText?: string;
  icon?: React.ComponentType<{ className?: string }>;
}> = ({ value, label, sub, badge, badgeVariant = 'secondary', percent, barColor, valueClass = 'text-gray-900', percentText, icon: Icon }) => {
  const cleanPct = (percent?.toString() || "0").replace(/%/g, "");
  const displayPercent = percentText || `${cleanPct}%`;

  const variantMap: Record<string, string> = {
    success: 'green',
    warning: 'yellow',
  };
  const finalVariant = variantMap[badgeVariant] || badgeVariant;

  return (
    <div className="text-left rtl:text-right">
      <div className="flex items-center gap-2 mb-1.5">
        <span className={`text-2xl font-bold ${valueClass}`}><SafeRender content={value} /></span>
        <Badge variant={finalVariant as VariantProps<typeof badgeVariants>['variant']} className="text-[10px] px-1.5 py-0 h-4.5 font-bold uppercase tracking-wider"><SafeRender content={badge} /></Badge>
      </div>
      <p className="text-[14px] font-bold text-slate-800 mb-0.5 uppercase tracking-tight flex items-center gap-2">
        {Icon && <Icon className="w-3.5 h-3.5 opacity-60" />}
        <SafeRender content={label} /> <span className="text-slate-400 font-normal">[{displayPercent}]</span>
      </p>
      <p className="text-[11px] text-slate-500 mb-3 font-medium leading-tight"><SafeRender content={sub} /></p>
      <div className="w-full h-1.5 bg-slate-100 rounded-full overflow-hidden">
        <div className={`h-full rounded-full transition-all duration-1000 ${barColor}`} style={{ width: `${cleanPct}%` }} />
      </div>
    </div>
  );
};

export const FeatSection: React.FC<{
  title: string;
  description?: string;
  children: React.ReactNode;
  badge?: string;
  icon?: React.ComponentType<{ className?: string; opacity?: number; shrink?: number | string }>;
  className?: string;
  gridCols?: string;
}> = ({ title, description, children, badge, icon: Icon, className = "", gridCols = "grid-cols-1 lg:grid-cols-2" }) => (
  <SettingCard className={`p-0 overflow-hidden mb-8 ${className}`}>
    <div className="pb-4 border-b border-slate-100 bg-slate-50/20 px-6 rounded-t-[5px]">
      <ModernCardHeader
        title={title}
        description={description}
        icon={Icon}
        className="!p-0 !pt-5 !border-none !bg-transparent"
        rightAction={badge && (
          <Badge variant="green" className="text-[10px] py-0.5 px-2 h-5 font-black uppercase tracking-widest">
            {badge}
          </Badge>
        )}
      />
    </div>
    <div className="p-6">
      <div className={`grid ${gridCols} gap-6`}>
        {children}
      </div>
    </div>
  </SettingCard>
);

export const FeatRow: React.FC<{
  icon: React.ComponentType<{ className?: string; opacity?: number; shrink?: number | string }>;
  title: string;
  desc: string;
  enabled: boolean;
  allowed: boolean;
  error?: string;
  onToggle: () => void;
  docs?: string;
  settingsUrl?: string;
  upgradeUrl?: string;
  pluginLink?: string;
  t?: {
    labelPro?: string;
    btnSettings?: string;
    btnUpgrade?: string;
    btnActivate?: string;
  };
}> = ({ icon: Icon, title, desc, enabled, allowed, error, onToggle, docs, settingsUrl, upgradeUrl, pluginLink, t = {} }) => {
  return (
    <div className={`flex flex-col p-6 rounded-[12px] border transition-all duration-300 h-full min-h-[140px] group relative ${!allowed || error
      ? 'bg-slate-50/50 grayscale opacity-70 border-slate-200 cursor-not-allowed'
      : enabled
        ? 'bg-emerald-50/30 border-emerald-200/60 shadow-[0_0_20px_rgba(16,185,129,0.03)]'
        : 'bg-white border-slate-200/60 hover:border-slate-300 hover:shadow-sm'
      }`}>


      <div className="flex items-start justify-between gap-4">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap mb-1">
            <div className={`flex items-center gap-2 text-base md:text-lg font-bold tracking-tight leading-tight ${enabled && allowed ? 'text-slate-800' : 'text-slate-500'}`}>
              {Icon && <Icon className={`w-5 h-5 shrink-0 ${enabled && allowed ? 'opacity-70 text-[#004449]' : 'opacity-30'}`} />}
              <SafeRender content={title} />
            </div>
            {!allowed && (
              <Badge variant="outline" className="text-[9px] px-1.5 py-0 h-4 font-black uppercase tracking-widest text-[#004449]/40 border-[#004449]/10 bg-[#004449]/5"><SafeRender content={t.labelPro || "PRO"} /></Badge>
            )}
            {error && !(allowed && pluginLink) && (
              <span className="flex items-center gap-1 text-[10px] text-amber-600 font-bold uppercase tracking-widest">
                <AlertCircle size={12} /> <SafeRender content={error} />
              </span>
            )}
          </div>
          <p className="text-xs font-medium text-slate-500 mt-1 leading-relaxed"><SafeRender content={desc} /></p>
        </div>

        <div className="flex items-center gap-3 flex-shrink-0 pt-1">
          {!allowed && upgradeUrl ? (
            <OutlineButton
              size="sm"
              className="h-8 text-[11px] font-black uppercase tracking-widest border-amber-200 text-amber-700 hover:bg-amber-50 shadow-none bg-amber-50/20"
              onClick={() => window.open(upgradeUrl, '_blank')}
            >
              <Crown size={12} /> <SafeRender content={t.btnUpgrade || "Upgrade"} />
            </OutlineButton>
          ) : allowed && error && pluginLink ? (
            <OutlineButton
              size="sm"
              className="h-8 text-[11px] font-black uppercase tracking-widest border-blue-200 text-blue-700 hover:bg-blue-50 shadow-none bg-blue-50/20"
              onClick={() => window.open(pluginLink, '_blank')}
            >
              <Download size={12} /> <SafeRender content={t.btnActivate || 'Activate'} />
            </OutlineButton>
          ) : (
            <div dir="ltr" className="flex items-center">
              <Switch
                checked={enabled && allowed}
                onCheckedChange={onToggle}
                disabled={!allowed || !!error}
              />
            </div>
          )}
        </div>
      </div>

      <div className="mt-0 pt-0 flex items-center justify-between">
        <div className="flex items-center gap-3">
          {enabled && allowed && (
            <div className="flex items-center gap-2 px-3 py-1 rounded-full border border-emerald-100/50 bg-emerald-50 text-emerald-600 text-[9px] font-black uppercase tracking-widest">
              <div className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse" />
              Active
            </div>
          )}
          {!enabled && allowed && !error && (
            <div className="flex items-center gap-2 px-3 py-1 rounded-full border border-slate-100 bg-slate-50 text-slate-400 text-[9px] font-black uppercase tracking-widest">
              Inert
            </div>
          )}
        </div>

        <div className="flex items-center gap-2">
          {enabled && allowed && settingsUrl && (
            <button
              type="button"
              className="h-8 px-3 rounded-[6px] text-[11px] font-bold text-slate-600 hover:text-slate-900 flex items-center gap-1.5 bg-slate-50 hover:bg-slate-100 border border-slate-200/50 transition-all active:scale-95"
              onClick={() => window.location.href = settingsUrl}
            >
              <Settings size={13} />
              <span><SafeRender content={t.btnSettings || "Configure"} /></span>
            </button>
          )}
          {docs && allowed && (
            <button
              type="button"
              className="h-8 w-8 rounded-[6px] flex items-center justify-center text-slate-400 hover:text-slate-700 bg-slate-50 hover:bg-slate-100 border border-slate-200/50 transition-all active:scale-95"
              onClick={() => window.open(docs, '_blank')}
            >
              <ExternalLink size={13} />
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export const ShortcodeGrid: React.FC<{
  title: string;
  description: string;
  shortcodes: { title: string; description: string; code: string; icon?: React.ComponentType<{ size?: number; className?: string; strokeWidth?: number }> }[];
}> = ({ title, description, shortcodes }) => {
  const handleCopy = (code: string) => {
    navigator.clipboard.writeText(code).then(() => {
      toast.success("Shortcode copied to clipboard!", {
        description: "You can now paste it into any page or theme builder block."
      });
    });
  };

  return (
    <SettingCard className="p-0 overflow-hidden">
      <ModernCardHeader
        title={title}
        description={description}
        icon={Copy}
      />
      <div className="p-6 md:p-8 bg-white">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {shortcodes.map((s, idx) => (
            <div key={idx} className="p-5 bg-white border border-slate-100 rounded-[5px] flex flex-col h-full group hover:border-[#004449]/20 hover:shadow-sm transition-all duration-300">
              <div className="mb-4">
                <div className="flex items-center gap-2.5 mb-1.5">
                  {s.icon && (
                    <div className="p-1.5 bg-slate-50 border border-slate-200/50 rounded-lg text-[#004449] group-hover:bg-[#004449] group-hover:text-white group-hover:border-[#004449] transition-all">
                      <s.icon size={13} strokeWidth={2.5} />
                    </div>
                  )}
                  <h4 className="text-[13px] font-bold text-slate-800 leading-tight tracking-tight">{s.title}</h4>
                </div>
                <p className="text-[11px] text-slate-500 font-medium leading-relaxed">{s.description}</p>
              </div>

              <div className="mt-auto flex items-center gap-2">
                <div className="flex-1 bg-slate-50/80 border border-slate-100 rounded-[5px] px-3 py-2 h-[34px] flex items-center overflow-hidden">
                  <code className="text-[10px] font-mono font-bold text-slate-600 truncate select-all">
                    {s.code}
                  </code>
                </div>
                <button
                  onClick={() => handleCopy(s.code)}
                  className="h-[34px] w-[34px] shrink-0 bg-white border border-[#dcdcde] text-slate-400 hover:text-[#004449] hover:border-[#004449]/30 rounded-[5px] flex items-center justify-center transition-all active:scale-95 shadow-sm"
                  title="Copy Shortcode"
                >
                  <Copy size={13} strokeWidth={2.5} />
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </SettingCard>
  );
};


export const HeaderSaveStatus: React.FC<{
  status: 'idle' | 'saving' | 'saved' | 'error' | 'unsaved';
}> = ({ status }) => (
  <div className="flex items-center gap-2 pr-2 border-r border-slate-200">
    <AnimatePresence mode="wait">
      {status === 'saving' && (
        <motion.div
          key="saving"
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0, scale: 0.9 }}
          className="flex items-center gap-1.5 px-3 py-1 bg-blue-50 text-blue-600 rounded-full border border-blue-100 animate-pulse"
        >
          <div className="w-1.5 h-1.5 bg-blue-500 rounded-full animate-bounce" />
          <span className="text-[10px] font-bold uppercase tracking-wider">Saving Changes...</span>
        </motion.div>
      )}
      {status === 'saved' && (
        <motion.div
          key="saved"
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0, scale: 0.9 }}
          className="flex items-center gap-1.5 px-3 py-1 bg-emerald-50 text-emerald-600 rounded-full border border-emerald-100"
        >
          <CheckCircle2 size={12} className="text-emerald-500" />
          <span className="text-[10px] font-bold uppercase tracking-wider">Changes Saved</span>
        </motion.div>
      )}
      {status === 'unsaved' && (
        <motion.div
          key="unsaved"
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0, scale: 0.9 }}
          className="flex items-center gap-1.5 px-3 py-1 bg-amber-50 text-amber-600 rounded-full border border-amber-100"
        >
          <div className="w-1.5 h-1.5 bg-amber-500 rounded-full animate-pulse" />
          <span className="text-[10px] font-bold uppercase tracking-wider">Unsaved Changes</span>
        </motion.div>
      )}
      {status === 'error' && (
        <motion.div
          key="error"
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0, scale: 0.9 }}
          className="flex items-center gap-1.5 px-3 py-1 bg-rose-50 text-rose-600 rounded-full border border-rose-100"
        >
          <AlertCircle size={12} className="text-rose-500" />
          <span className="text-[10px] font-bold uppercase tracking-wider">Save Failed</span>
        </motion.div>
      )}
    </AnimatePresence>
  </div>
);


export const ModernCardHeader: React.FC<{
  title: React.ReactNode;
  description?: React.ReactNode;
  icon?: React.ElementType;
  iconPath?: string;
  rightAction?: React.ReactNode;
  className?: string;
}> = ({ title, description, icon: Icon, iconPath, rightAction, className = "" }) => (
  <div className={`pt-4 pb-4 border-b border-slate-100 bg-slate-50/20 px-6 rounded-t-[5px] ${className}`}>
    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
      <div>
        <div className="text-base md:text-lg font-bold flex items-center gap-2 text-slate-800">
          {iconPath ? (
            <img src={iconPath} className="w-5 h-5 object-contain opacity-80" alt="" />
          ) : Icon && <Icon className="w-5 h-5 opacity-70" />}
          <SafeRender content={title} />
        </div>
        {description && (
          <div className="text-xs font-medium text-slate-500 mt-0.5">
            <SafeRender content={description} />
          </div>
        )}
      </div>
      {rightAction && <div className="shrink-0">{rightAction}</div>}
    </div>
  </div>
);

export const SettingsTabContent: React.FC<{
  id: string;
  activeTab: string;
  children: React.ReactNode;
}> = ({ id, activeTab, children }) => {
  return (
    <AnimatePresence mode="wait">
      {id === activeTab && (
        <motion.div
          key={id}
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -10 }}
          transition={{ duration: 0.2 }}
          className="space-y-6"
        >
          {children}
        </motion.div>
      )}
    </AnimatePresence>
  );
};

export const SettingsGrid: React.FC<{
  children: React.ReactNode;
  cols?: 1 | 2 | 3;
  gap?: number;
  className?: string;
}> = ({ children, cols = 2, gap = 6, className }) => {
  const gridCols = {
    1: 'grid-cols-1',
    2: 'grid-cols-1 lg:grid-cols-2',
    3: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
  }[cols];

  return (
    <div className={cn(`grid ${gridCols} gap-${gap}`, className)}>
      {children}
    </div>
  );
};

export const SaveWithStatus: React.FC<{
  saveStatus: 'idle' | 'saving' | 'saved' | 'error';
  hasUnsavedChanges: boolean;
  isSaving: boolean;
  onSave: () => void;
  t?: {
    saving?: string;
    synchronized?: string;
    unsaved?: string;
    saveChanges?: string;
  };
}> = ({ saveStatus, hasUnsavedChanges, isSaving, onSave, t = {} }) => {
  return (
    <div className="flex items-center gap-3">
      <AnimatePresence mode="wait">
        {saveStatus === 'saving' && (
          <motion.div
            initial={{ opacity: 0, x: 10 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -10 }}
            className="flex items-center gap-2 px-3 py-1.5 bg-indigo-50 text-indigo-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-indigo-100/50"
          >
            <span className="w-1.5 h-1.5 bg-indigo-500 rounded-full animate-pulse" />
            {t.saving || 'Saving...'}
          </motion.div>
        )}
        {saveStatus === 'saved' && (
          <motion.div
            initial={{ opacity: 0, x: 10 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -10 }}
            className="flex items-center gap-2 px-3 py-1.5 bg-emerald-50 text-emerald-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-emerald-100/50"
          >
            <span className="w-1.5 h-1.5 bg-emerald-500 rounded-full" />
            {t.synchronized || 'Synchronized'}
          </motion.div>
        )}
        {hasUnsavedChanges && saveStatus === 'idle' && (
          <motion.div
            initial={{ opacity: 0, x: 10 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -10 }}
            className="flex items-center gap-2 px-3 py-1.5 bg-amber-50 text-amber-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-amber-100/50"
          >
            <span className="w-1.5 h-1.5 bg-amber-500 rounded-full animate-ping" />
            {t.unsaved || 'Unsaved Changes'}
          </motion.div>
        )}
        {saveStatus === 'error' && (
          <motion.div
            initial={{ opacity: 0, x: 10 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -10 }}
            className="flex items-center gap-2 px-3 py-1.5 bg-rose-50 text-rose-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-rose-100/50"
          >
            <span className="w-1.5 h-1.5 bg-rose-500 rounded-full" />
            Error Saving
          </motion.div>
        )}
      </AnimatePresence>

      <AdminButton
        onClick={onSave}
        loading={isSaving}
        icon={Save}
      >
        {isSaving ? (t.saving || 'Saving...') : (t.saveChanges || 'Save Changes')}
      </AdminButton>
    </div>
  );
};
