/* Shared floating widgets for the Helptyfy UI kits.
   Exposes window.AIPanel, window.Customizer, window.LanguageMenu.
   Depends on window.Icons and the DS bundle (AIOrb, IconButton, Button). */
;(function(){
const { useState, useEffect, useRef } = React;

const ACCENTS = [
  { id: 'violet', label: 'Violet', a: '#8b5cf6', a2: '#22d3ee', strong: '#6d28d9' },
  { id: 'indigo', label: 'Indigo', a: '#6366f1', a2: '#22d3ee', strong: '#4338ca' },
  { id: 'blue',   label: 'Blue',   a: '#3b82f6', a2: '#22d3ee', strong: '#1d4ed8' },
  { id: 'cyan',   label: 'Cyan',   a: '#06b6d4', a2: '#818cf8', strong: '#0e7490' },
  { id: 'teal',   label: 'Teal',   a: '#14b8a6', a2: '#22d3ee', strong: '#0f766e' },
  { id: 'emerald',label: 'Emerald',a: '#10b981', a2: '#22d3ee', strong: '#047857' },
  { id: 'lime',   label: 'Lime',   a: '#84cc16', a2: '#22d3ee', strong: '#4d7c0f' },
  { id: 'amber',  label: 'Amber',  a: '#f59e0b', a2: '#fb7185', strong: '#b45309' },
  { id: 'orange', label: 'Orange', a: '#f97316', a2: '#fb7185', strong: '#c2410c' },
  { id: 'rose',   label: 'Rose',   a: '#fb7185', a2: '#c084fc', strong: '#e11d48' },
  { id: 'fuchsia',label: 'Fuchsia',a: '#d946ef', a2: '#22d3ee', strong: '#a21caf' },
  { id: 'slate',  label: 'Slate',  a: '#64748b', a2: '#94a3b8', strong: '#475569' },
];

const THEMES = [
  { id: 'system', label: 'System' },
  { id: 'light',  label: 'Light' },
  { id: 'dark',   label: 'Dark' },
];
const prefersDark = () => window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

function applyAccent(id) {
  const p = ACCENTS.find(x => x.id === id) || ACCENTS[0];
  const r = document.documentElement.style;
  r.setProperty('--accent', p.a);
  r.setProperty('--accent-2', p.a2);
  r.setProperty('--accent-strong', p.strong);
}
function applyTheme(mode) {
  const resolved = mode === 'system' ? (prefersDark() ? 'dark' : 'light') : mode;
  document.documentElement.setAttribute('data-theme', resolved);
}

/* ---------------- Customizer ---------------- */
function Customizer() {
  const { IconButton } = window.HelptyDesignSystem_56c945;
  const { Icons } = window;
  const [open, setOpen] = useState(false);
  const [theme, setTheme] = useState(() => localStorage.getItem('helpty-theme') || 'dark');
  const [accent, setAccent] = useState(() => localStorage.getItem('helpty-accent') || 'violet');

  useEffect(() => {
    applyTheme(theme); localStorage.setItem('helpty-theme', theme);
    if (theme !== 'system' || !window.matchMedia) return;
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const h = () => applyTheme('system');
    mq.addEventListener('change', h);
    return () => mq.removeEventListener('change', h);
  }, [theme]);
  useEffect(() => { applyAccent(accent); localStorage.setItem('helpty-accent', accent); }, [accent]);

  return (
    <div style={{ position: 'fixed', left: 22, bottom: 22, zIndex: 1200 }}>
      {open && (
        <div className="hl-popover" style={{ position: 'absolute', bottom: 56, left: 0, width: 248, padding: 16, borderRadius: 'var(--radius-lg)' }}>
          <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 10 }}>Appearance</div>
          <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--surface-glass)', borderRadius: 999, marginBottom: 14 }}>
            {THEMES.map(m => (
              <button key={m.id} onClick={() => setTheme(m.id)} style={{
                flex: 1, height: 32, border: 'none', borderRadius: 999, cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                fontSize: 12.5, fontWeight: 600, fontFamily: 'var(--font-sans)',
                background: theme === m.id ? 'var(--accent-gradient)' : 'transparent',
                color: theme === m.id ? '#fff' : 'var(--text-secondary)',
                boxShadow: theme === m.id ? 'var(--glow-accent)' : 'none',
              }}>
                {m.id === 'light' ? <Icons.Sun size={14} /> : m.id === 'dark' ? <Icons.Moon size={14} /> : <Icons.Monitor size={14} />}{m.label}
              </button>
            ))}
          </div>
          <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 10 }}>Accent</div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {ACCENTS.map(p => (
              <button key={p.id} onClick={() => setAccent(p.id)} title={p.label} aria-label={p.label} style={{
                width: 28, height: 28, borderRadius: '50%', cursor: 'pointer',
                background: `linear-gradient(135deg, ${p.a}, ${p.a2})`,
                border: accent === p.id ? '2px solid var(--text-primary)' : '2px solid transparent',
                boxShadow: accent === p.id ? `0 0 0 2px var(--bg-base) inset, 0 6px 16px -4px ${p.a}` : 'none',
              }} />
            ))}
          </div>
        </div>
      )}
      <IconButton label="Customize appearance" variant="glass" size="lg" onClick={() => setOpen(o => !o)}>
        {open ? <Icons.X size={18} /> : <Icons.Sliders size={18} />}
      </IconButton>
    </div>
  );
}

/* ---------------- Language menu ---------------- */
const LANGS = [
  { code: 'EN', label: 'English' },
  { code: 'BG', label: 'Български' },
  { code: 'ES', label: 'Español' },
  { code: 'DE', label: 'Deutsch' },
  { code: 'FR', label: 'Français' },
];
function LanguageMenu({ value = 'EN', onChange }) {
  const { Icons } = window;
  const [open, setOpen] = useState(false);
  const ref = useRef();
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: 'inline-flex', alignItems: 'center', gap: 7, height: 40, padding: '0 12px',
        background: 'var(--surface-glass)', border: '1px solid var(--border-glass)', borderRadius: 999,
        color: 'var(--text-secondary)', cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
      }}>
        <Icons.Globe size={16} />{value}<Icons.ChevronDown size={14} />
      </button>
      {open && (
        <div className="hl-popover" style={{ position: 'absolute', right: 0, top: 48, width: 184, padding: 6, borderRadius: 'var(--radius-md)', zIndex: 1300 }}>
          {LANGS.map(l => (
            <button key={l.code} onClick={() => { onChange && onChange(l.code); setOpen(false); }} style={{
              width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '9px 12px', border: 'none', borderRadius: 10, cursor: 'pointer',
              background: value === l.code ? 'var(--accent-soft)' : 'transparent',
              color: value === l.code ? 'var(--text-accent)' : 'var(--text-primary)',
              fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
            }}>
              <span>{l.label}</span><span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, opacity: .7 }}>{l.code}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------------- Helptyfy AI panel ---------------- */
function AIPanel({ strings = {} }) {
  const { AIOrb, IconButton } = window.HelptyDesignSystem_56c945;
  const { Icons } = window;
  const [open, setOpen] = useState(false);
  const s = {
    title: 'Helptyfy AI', sub: 'Here to find your people',
    greet: 'Hi! Tell me what you need right now and I\u2019ll find the people who fit \u2014 and write you a reason why.',
    chips: ['Find me a co-founder', 'Who needs my SEO help?', 'Draft my listing'],
    placeholder: 'Describe what you have or need\u2026',
    ...strings,
  };
  const [msgs, setMsgs] = useState([{ role: 'ai', text: s.greet }]);
  const [draft, setDraft] = useState('');
  const bodyRef = useRef();
  useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [msgs, open]);

  const send = (text) => {
    const t = (text || draft).trim();
    if (!t) return;
    setDraft('');
    setMsgs(m => [...m, { role: 'me', text: t }]);
    setTimeout(() => setMsgs(m => [...m, {
      role: 'ai',
      match: { name: 'Mara Devic', role: 'Brand strategist', pct: 92, why: 'She needs the growth engineering you offer, and she has the brand positioning you said you\u2019re missing.' },
      text: 'Here\u2019s a strong match for that:',
    }]), 650);
  };

  return (
    <div style={{ position: 'fixed', right: 22, bottom: 22, zIndex: 1200, display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 14 }}>
      {open && (
        <div className="hl-glass-strong" style={{ width: 360, maxWidth: 'calc(100vw - 44px)', height: 480, maxHeight: 'calc(100vh - 120px)', borderRadius: 'var(--radius-xl)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 16, borderBottom: '1px solid var(--border-glass)' }}>
            <AIOrb size={38} pulse={false} style={{ pointerEvents: 'none' }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 800, fontSize: 15, letterSpacing: '-.02em' }}>{s.title}</div>
              <div style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{s.sub}</div>
            </div>
            <IconButton label="Close" onClick={() => setOpen(false)}><Icons.X size={18} /></IconButton>
          </div>
          <div ref={bodyRef} style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {msgs.map((m, i) => (
              <div key={i} style={{ alignSelf: m.role === 'me' ? 'flex-end' : 'flex-start', maxWidth: '85%' }}>
                <div style={{
                  padding: '10px 13px', borderRadius: 16, fontSize: 13.5, lineHeight: 1.5,
                  background: m.role === 'me' ? 'var(--accent-gradient)' : 'var(--surface-glass)',
                  color: m.role === 'me' ? '#fff' : 'var(--text-primary)',
                  border: m.role === 'me' ? 'none' : '1px solid var(--border-glass)',
                  borderBottomRightRadius: m.role === 'me' ? 4 : 16,
                  borderBottomLeftRadius: m.role === 'me' ? 16 : 4,
                }}>{m.text}</div>
                {m.match && (
                  <div className="hl-glass" style={{ marginTop: 8, padding: 12, borderRadius: 14 }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                      <strong style={{ fontSize: 14 }}>{m.match.name}</strong>
                      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-accent)', fontWeight: 700 }}>{m.match.pct}%</span>
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 4 }}>{m.match.role}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--text-primary)', lineHeight: 1.5 }}><em>{m.match.why}</em></div>
                  </div>
                )}
              </div>
            ))}
          </div>
          <div style={{ padding: 12, borderTop: '1px solid var(--border-glass)' }}>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 10 }}>
              {s.chips.map(c => (
                <button key={c} onClick={() => send(c)} style={{
                  fontSize: 12, fontWeight: 600, padding: '6px 10px', borderRadius: 999, cursor: 'pointer',
                  background: 'var(--surface-glass)', border: '1px solid var(--border-glass)', color: 'var(--text-secondary)', fontFamily: 'var(--font-sans)',
                }}>{c}</button>
              ))}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--surface-glass)', border: '1px solid var(--border-glass)', borderRadius: 999, padding: '4px 4px 4px 14px' }}>
              <input value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()}
                placeholder={s.placeholder} style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', color: 'var(--text-primary)', fontFamily: 'var(--font-sans)', fontSize: 13.5 }} />
              <IconButton label="Send" variant="accent" onClick={() => send()}><Icons.Send size={16} /></IconButton>
            </div>
          </div>
        </div>
      )}
      <AIOrb size={60} onClick={() => setOpen(o => !o)} />
    </div>
  );
}

Object.assign(window, { AIPanel, Customizer, LanguageMenu, LANGS, ACCENTS });
})();
