import { useState, useEffect, useRef } from 'react';

const THEMES = [
  { key: 'default', label: 'Pure White',  bg: '#ffffff', surface: '#f7f7f7' },
  { key: 'warm',    label: 'Warm White',  bg: '#fefcf8', surface: '#faf8f3' },
  { key: 'cool',    label: 'Cool White',  bg: '#f8fafc', surface: '#f1f5f9' },
  { key: 'gray',    label: 'Soft Gray',   bg: '#f4f4f5', surface: '#ffffff' },
  { key: 'paper',   label: 'Paper',       bg: '#fdf8f0', surface: '#f5f0e8' },
  { key: 'dark',    label: 'Dark',        bg: '#0f0f0f', surface: '#1a1a1a' },
];

const ACCENTS = [
  { key: 'default', color: '#2563eb', label: 'Blue'   },
  { key: 'indigo',  color: '#4f46e5', label: 'Indigo' },
  { key: 'violet',  color: '#7c3aed', label: 'Violet' },
  { key: 'teal',    color: '#0d9488', label: 'Teal'   },
  { key: 'rose',    color: '#e11d48', label: 'Rose'   },
  { key: 'orange',  color: '#ea580c', label: 'Orange' },
];

function load() {
  try {
    return {
      theme:  localStorage.getItem('seo_theme')  || 'default',
      accent: localStorage.getItem('seo_accent') || 'default',
    };
  } catch { return { theme: 'default', accent: 'default' }; }
}

function apply({ theme, accent }) {
  const root = document.documentElement;
  root.setAttribute('data-theme',  theme  === 'default' ? '' : theme);
  root.setAttribute('data-accent', accent === 'default' ? '' : accent);
  try {
    localStorage.setItem('seo_theme',  theme);
    localStorage.setItem('seo_accent', accent);
  } catch {}
}

// Call once on app load
export function initTheme() {
  apply(load());
}

export default function ThemePicker() {
  const [open, setOpen]     = useState(false);
  const [theme, setTheme]   = useState(load().theme);
  const [accent, setAccent] = useState(load().accent);
  const ref = useRef();

  useEffect(() => {
    const handler = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const handleTheme = (key) => {
    setTheme(key);
    apply({ theme: key, accent });
  };

  const handleAccent = (key) => {
    setAccent(key);
    apply({ theme, accent: key });
  };

  const activeTheme  = THEMES.find(t => t.key === theme)  || THEMES[0];
  const activeAccent = ACCENTS.find(a => a.key === accent) || ACCENTS[0];

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      {/* Trigger button */}
      <button onClick={() => setOpen(o => !o)}
        title="Change theme"
        style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, padding: '3px 10px', borderRadius: 20,
          border: '0.5px solid var(--border2)', background: open ? 'var(--surface2)' : 'transparent',
          color: 'var(--text2)', cursor: 'pointer', transition: 'all .12s' }}>
        {/* Mini preview */}
        <span style={{ display: 'flex', gap: 2 }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: activeTheme.bg, border: '0.5px solid var(--border2)' }} />
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: activeAccent.color }} />
        </span>
        Theme
      </button>

      {/* Popover */}
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 8px)', right: 0, zIndex: 300,
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 12, padding: 16, width: 240,
          boxShadow: '0 8px 30px rgba(0,0,0,.12)',
        }}>
          {/* Background theme */}
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--text3)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 8 }}>
            Background
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 6, marginBottom: 16 }}>
            {THEMES.map(t => (
              <button key={t.key} onClick={() => handleTheme(t.key)}
                title={t.label}
                style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, padding: '8px 4px', borderRadius: 8, cursor: 'pointer',
                  border: `1.5px solid ${theme === t.key ? activeAccent.color : 'var(--border)'}`,
                  background: theme === t.key ? activeAccent.color + '10' : 'transparent',
                  transition: 'all .12s' }}>
                {/* Preview swatch */}
                <div style={{ width: 36, height: 26, borderRadius: 5, background: t.bg, border: '0.5px solid rgba(0,0,0,.1)', overflow: 'hidden', position: 'relative' }}>
                  <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 10, background: t.surface, borderTop: '0.5px solid rgba(0,0,0,.06)' }} />
                  <div style={{ position: 'absolute', top: 4, left: 4, width: 10, height: 3, borderRadius: 2, background: activeAccent.color + 'aa' }} />
                  <div style={{ position: 'absolute', top: 9, left: 4, width: 16, height: 2, borderRadius: 1, background: 'rgba(0,0,0,.15)' }} />
                </div>
                <span style={{ fontSize: 10, color: theme === t.key ? activeAccent.color : 'var(--text2)', fontWeight: theme === t.key ? 600 : 400, lineHeight: 1.2, textAlign: 'center' }}>
                  {t.label}
                </span>
              </button>
            ))}
          </div>

          {/* Accent color */}
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--text3)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 8 }}>
            Accent color
          </div>
          <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap' }}>
            {ACCENTS.map(a => (
              <button key={a.key} onClick={() => handleAccent(a.key)}
                title={a.label}
                style={{ width: 28, height: 28, borderRadius: '50%', background: a.color, cursor: 'pointer',
                  border: `2.5px solid ${accent === a.key ? 'var(--text)' : 'transparent'}`,
                  boxShadow: accent === a.key ? `0 0 0 1px ${a.color}` : 'none',
                  transition: 'all .12s' }} />
            ))}
          </div>

          <div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
            Saved automatically to your browser
          </div>
        </div>
      )}
    </div>
  );
}
