const { useEffect, useRef, useState } = React;

const LucideIcon = ({ name, size = 18, className = "" }) => {
  const iconDef = window.lucide?.icons?.[name];
  const iconNode = Array.isArray(iconDef)
    ? iconDef
    : Array.isArray(iconDef?.iconNode)
      ? iconDef.iconNode
      : null;
  if (!iconNode) return <span className={className}></span>;
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
      {iconNode.map((child, index) => {
        const [tag, attrs] = child;
        return React.createElement(tag, { ...attrs, key: index });
      })}
    </svg>
  );
};

const Settings = (props) => <LucideIcon name="Settings" {...props} />;
const ChevronRight = (props) => <LucideIcon name="ChevronRight" {...props} />;
const X = (props) => <LucideIcon name="X" {...props} />;

const THEME_OPTIONS = [
  { key: 'light', label: 'Light' },
  { key: 'dark', label: 'Dark' },
  { key: 'system', label: 'System' },
];

const THEME_LABELS = {
  light: 'Light',
  dark: 'Dark',
  system: 'System'
};

const useSharedThemePreference = () => (
  typeof window.__hsUseThemePreference === 'function'
    ? window.__hsUseThemePreference()
    : { preference: 'light', setTheme: () => {}, isDark: false }
);

const WebsiteSettingsButton = ({ onClick, className = '', variant = 'drawer', title = 'Website Settings' }) => {
  if (variant === 'floating') {
    return (
      <button
        type="button"
        onClick={onClick}
        className={`inline-flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/10 text-white shadow-xl backdrop-blur-md transition-all hover:bg-white/20 hover:scale-105 focus:outline-none focus:ring-2 focus:ring-[#DFFF00] focus:ring-offset-2 focus:ring-offset-[#2D3436] ${className}`.trim()}
        title={title}
        aria-label={title}
      >
        <Settings size={18} />
      </button>
    );
  }

  return (
    <button
      type="button"
      onClick={onClick}
      className={`inline-flex h-12 w-12 items-center justify-center rounded-xl border border-white/10 bg-white/10 text-white transition-all hover:bg-white/20 hover:scale-105 focus:outline-none focus:ring-2 focus:ring-[#DFFF00] focus:ring-offset-2 focus:ring-offset-transparent ${className}`.trim()}
      title={title}
      aria-label={title}
    >
      <Settings size={18} />
    </button>
  );
};

const WebsiteSettingsModal = ({ onClose, title = 'Website Settings' }) => {
  const panelRef = useRef(null);
  const { preference, setTheme } = useSharedThemePreference();
  const [draftPreference, setDraftPreference] = useState(preference);
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    setDraftPreference(preference);
  }, [preference]);

  useEffect(() => {
    const handleEsc = (event) => {
      if (event.key === 'Escape') onClose();
    };
    const handleOutside = (event) => {
      if (panelRef.current && !panelRef.current.contains(event.target)) onClose();
    };
    document.addEventListener('keydown', handleEsc);
    document.addEventListener('mousedown', handleOutside);
    document.addEventListener('touchstart', handleOutside);
    return () => {
      document.removeEventListener('keydown', handleEsc);
      document.removeEventListener('mousedown', handleOutside);
      document.removeEventListener('touchstart', handleOutside);
    };
  }, [onClose]);

  const currentLabel = THEME_LABELS[preference] || 'Light';
  const draftLabel = THEME_LABELS[draftPreference] || 'Light';
  const hasChanges = draftPreference !== preference;

  const handleSave = () => {
    if (!hasChanges) return;
    setTheme(draftPreference);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[#2D3436]/50 backdrop-blur-sm p-6 animate-in fade-in duration-200" onClick={onClose}>
      <div ref={panelRef} className="bg-white rounded-2xl shadow-xl p-8 max-w-sm w-full relative text-center" onClick={(event) => event.stopPropagation()}>
        <button onClick={onClose} className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#1A4D2E] focus:ring-offset-1" aria-label="Close Website Settings">
          <X size={20} />
        </button>
        <div className="w-16 h-16 bg-[#1A4D2E]/10 rounded-full flex items-center justify-center mx-auto mb-4 text-[#1A4D2E]">
          <Settings size={30} />
        </div>
        <h3 className="font-heading font-bold text-xl text-[#2D3436] mb-2">{title}</h3>
        <p className="text-gray-500 text-sm mb-6">Adjust shared storefront preferences.</p>

        <div className="text-left bg-gray-50 p-4 rounded-xl border border-gray-100 mb-4">
          <button
            type="button"
            onClick={() => setExpanded((value) => !value)}
            className="w-full flex items-center justify-between gap-3 text-left"
            aria-expanded={expanded}
            aria-controls="website-settings-theme-switcher"
          >
            <div className="flex items-center gap-3 min-w-0">
              <span className="inline-flex h-8 w-8 items-center justify-center rounded-full bg-[#1A4D2E]/10 text-[#1A4D2E] flex-shrink-0">
                <ChevronRight size={16} className={expanded ? 'rotate-90 transition-transform' : 'transition-transform'} />
              </span>
              <div className="min-w-0">
                <p className="font-bold text-[#2D3436] leading-tight">
                  Theme Switcher <span className="text-xs font-medium text-gray-400">({currentLabel})</span>
                </p>
              </div>
            </div>
          </button>

          {expanded && (
            <div id="website-settings-theme-switcher" className="mt-4 space-y-2">
              <label className="block text-xs font-bold uppercase tracking-widest text-gray-400">Select theme</label>
              <select
                value={draftPreference}
                onChange={(event) => setDraftPreference(event.target.value)}
                className="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm font-semibold text-[#2D3436] shadow-sm focus:outline-none focus:ring-2 focus:ring-[#1A4D2E] focus:border-[#1A4D2E]"
              >
                {THEME_OPTIONS.map((option) => (
                  <option key={option.key} value={option.key}>
                    {option.label}
                  </option>
                ))}
              </select>
              <p className="text-xs text-gray-400">
                Selected: <span className="font-semibold text-gray-500">{draftLabel}</span>
              </p>
            </div>
          )}
        </div>

        <div className="flex items-center justify-between gap-3">
          <p className={`text-xs text-left ${hasChanges ? 'text-[#1A4D2E]' : 'text-gray-400'}`}>
            {hasChanges ? 'Save changes to apply the new theme.' : 'No changes to save.'}
          </p>
          <button
            type="button"
            onClick={handleSave}
            disabled={!hasChanges}
            className={`px-5 py-3 rounded-xl font-bold text-sm transition-all focus:outline-none focus:ring-2 focus:ring-[#1A4D2E] focus:ring-offset-2 ${
              hasChanges
                ? 'bg-[#1A4D2E] text-white shadow-lg hover:bg-[#143d23]'
                : 'bg-gray-100 text-gray-400 cursor-not-allowed'
            }`}
          >
            Save Changes
          </button>
        </div>
      </div>
    </div>
  );
};

window.HSNexusWebsiteSettings = {
  WebsiteSettingsButton,
  WebsiteSettingsModal,
  themeOptions: THEME_OPTIONS
};
