/* Flow-OS interactive prototype — Daxa-inspired */
const { useState: useS, useEffect: useE, useMemo: useM, useRef: useR, createContext, useContext } = React;

// ============= ROUTER =============
const RouteCtx = createContext(null);
function useRoute() { return useContext(RouteCtx); }

// ============= MOCK DATA =============
const TEAMS = [
  { id: 'eng-be', name: 'Engineering', sub: 'Backend', size: 9, flow: 78, recovery: 74, hrv: 4, sleep: '7h 32m', delta: +6, trend: [60, 64, 68, 70, 72, 75, 78], status: 'green', alerts: 0 },
  { id: 'mkt', name: 'Marketing', sub: 'Brand', size: 7, flow: 78, recovery: 76, hrv: 5, sleep: '7h 41m', delta: +4, trend: [70, 72, 74, 75, 76, 77, 78], status: 'green', alerts: 0 },
  { id: 'design', name: 'Diseño', sub: 'Producto', size: 6, flow: 73, recovery: 70, hrv: 2, sleep: '7h 18m', delta: +1, trend: [70, 71, 72, 73, 73, 74, 73], status: 'green', alerts: 0 },
  { id: 'eng-fe', name: 'Engineering', sub: 'Frontend', size: 12, flow: 71, recovery: 68, hrv: 1, sleep: '7h 08m', delta: +2, trend: [62, 65, 67, 68, 70, 71, 71], status: 'green', alerts: 0 },
  { id: 'legal', name: 'Legal', sub: '', size: 5, flow: 70, recovery: 71, hrv: 1, sleep: '7h 14m', delta: 0, trend: [69, 69, 70, 70, 70, 71, 70], status: 'green', alerts: 0 },
  { id: 'ops', name: 'Operaciones', sub: '', size: 8, flow: 67, recovery: 65, hrv: 0, sleep: '7h 02m', delta: -1, trend: [65, 66, 67, 67, 67, 68, 67], status: 'amber', alerts: 1 },
  { id: 'cs', name: 'Customer Success', sub: '', size: 11, flow: 59, recovery: 61, hrv: -1, sleep: '6h 58m', delta: -3, trend: [64, 63, 62, 60, 59, 59, 59], status: 'amber', alerts: 1 },
  { id: 'sales', name: 'Ventas', sub: 'EMEA', size: 22, flow: 54, recovery: 56, hrv: -3, sleep: '6h 42m', delta: -8, trend: [66, 64, 61, 60, 57, 55, 54], status: 'amber', alerts: 2 },
  { id: 'product', name: 'Producto', sub: 'Madrid', size: 14, flow: 41, recovery: 58, hrv: -6, sleep: '6h 24m', delta: -19, trend: [68, 64, 60, 55, 50, 45, 41], status: 'red', alerts: 3 }
];

const SEMAPHORE_GRADIENT = 'linear-gradient(135deg, #4fd693 0%, #2ea66a 100%)';

// ============= NAV =============
function TopNav() {
  const route = useRoute();
  const [searchOpen, setSearchOpen] = useS(false);
  const items = [
    { id: 'overview', l: 'Overview' },
    { id: 'departments', l: 'Departamentos' },
    { id: 'recommendations', l: 'Recomendaciones' },
    { id: 'reports', l: 'Informes' }
  ];

  // ⌘K / Ctrl+K shortcut
  useE(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setSearchOpen(s => !s);
      } else if (e.key === 'Escape') {
        setSearchOpen(false);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  return (
    <>
    <div className="topnav" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 32px', borderBottom: '1px solid var(--line)', gap: 24 }}>
      <div className="topnav-left" style={{ display: 'flex', alignItems: 'center', gap: 32, minWidth: 0 }}>
        <a href="#" onClick={(e) => { e.preventDefault(); route.go('overview'); }} className="topnav-brand" style={{
          display: 'flex', alignItems: 'center', textDecoration: 'none', color: 'var(--ink)', flexShrink: 0, marginLeft: 20
        }}>
          <img src="assets/flow-logo.png" alt="Flow-OS" width="52" height="52" style={{ display: 'block', objectFit: 'contain' }} />
        </a>
        <nav className="topnav-tabs" style={{ display: 'flex', gap: 6, background: 'transparent', minWidth: 0 }}>
          {items.map(i => {
            const active = route.page === i.id;
            return (
              <button key={i.id} onClick={() => route.go(i.id)} style={{
                padding: '10px 18px', borderRadius: 999, border: 'none',
                background: active ? 'var(--ink)' : 'transparent',
                color: active ? '#fff' : 'var(--ink-2)',
                fontSize: 14, fontFamily: 'var(--sans)', fontWeight: 500, cursor: 'pointer',
                whiteSpace: 'nowrap'
              }}>{i.l}</button>
            );
          })}
        </nav>
      </div>
      <div className="topnav-right" style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
        <button onClick={() => setSearchOpen(true)} style={iconBtn} title="Buscar (⌘K)">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.35-4.35"/></svg>
        </button>
        <button onClick={() => route.toggleAi()} data-ai-trigger="1" className="topnav-ai-btn topnav-mihai-btn" aria-label="Pregunta a Mihai" title="Pregunta a Mihai" style={{
          ...iconBtn,
          background: route.aiOpen ? 'var(--ink)' : 'var(--bg-card)'
        }}>
          <img src="assets/mihai-glyph.png" alt="" width="26" height="26" style={{ display: 'block', objectFit: 'contain', filter: route.aiOpen ? 'invert(1) brightness(2)' : 'none' }}/>
        </button>
        <button style={iconBtn}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>
          <span style={{ position: 'absolute', top: 6, right: 6, width: 8, height: 8, borderRadius: '50%', background: 'var(--red)', border: '2px solid var(--bg-card)' }}></span>
        </button>
        <div className="topnav-user" style={{ display: 'flex', alignItems: 'center', gap: 10, paddingLeft: 14, borderLeft: '1px solid var(--line)' }}>
          <Avatar initials="PF" photo={PF_PHOTO} />
          <div className="topnav-user-meta">
            <div style={{ fontSize: 13, fontWeight: 500 }}>P. Ferrer</div>
            <div className="mono" style={{ fontSize: 9, color: 'var(--ink-3)' }}>CEO</div>
          </div>
        </div>
      </div>
    </div>
    {searchOpen && <SearchModal onClose={() => setSearchOpen(false)} />}
    </>
  );
}

// ============= SEARCH MODAL (command palette) =============
function SearchModal({ onClose }) {
  const route = useRoute();
  const [q, setQ] = useS('');
  const inputRef = useR(null);
  useE(() => { inputRef.current && inputRef.current.focus(); }, []);

  const ql = q.trim().toLowerCase();
  const teamHits = (typeof TEAMS !== 'undefined' ? TEAMS : [])
    .filter(t => !ql || (`${t.name} ${t.sub || ''}`.toLowerCase().includes(ql)));
  const pageHits = [
    { id: 'overview', l: 'Overview', d: 'Panel global · Flow Score' },
    { id: 'departments', l: 'Departamentos', d: 'Vista por equipo · mapa de calor' },
    { id: 'recommendations', l: 'Recomendaciones', d: 'Acciones priorizadas por IA' },
    { id: 'reports', l: 'Informes', d: 'Reportes y exportaciones' }
  ].filter(p => !ql || p.l.toLowerCase().includes(ql) || p.d.toLowerCase().includes(ql));

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(15,15,14,0.45)', backdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      paddingTop: 'min(15vh, 140px)'
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 'min(640px, 92vw)', background: 'var(--bg-elev)',
        borderRadius: 18, border: '1px solid var(--line)',
        boxShadow: '0 32px 80px rgba(0,0,0,0.25)',
        overflow: 'hidden', display: 'flex', flexDirection: 'column'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '18px 22px', borderBottom: '1px solid var(--line)' }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--ink-3)" strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.35-4.35"/></svg>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)}
            placeholder="Buscar equipo, alerta, persona, página…"
            style={{ flex: 1, border: 'none', background: 'transparent', fontSize: 16, fontFamily: 'var(--sans)', outline: 'none', color: 'var(--ink)' }} />
          <button onClick={onClose} aria-label="Cerrar" style={{ width: 32, height: 32, borderRadius: 8, border: '1px solid var(--line)', background: 'var(--bg)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-2)', flexShrink: 0 }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
          </button>
        </div>

        <div style={{ maxHeight: '50vh', overflowY: 'auto' }}>
          {teamHits.length > 0 && (
            <div style={{ padding: '12px 14px 6px' }}>
              <div className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', color: 'var(--ink-4)', padding: '4px 10px' }}>EQUIPOS</div>
              {teamHits.map(t => (
                <button key={t.id} onClick={() => { route.goDept(t.id); onClose(); }} style={searchRow}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: t.status === 'red' ? 'var(--red)' : t.status === 'amber' ? 'var(--amber)' : 'var(--green)', flexShrink: 0 }}></span>
                  <span style={{ flex: 1, textAlign: 'left', fontSize: 14 }}>{t.name}{t.sub ? ` · ${t.sub}` : ''}</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>Flow {t.flow}</span>
                </button>
              ))}
            </div>
          )}
          {pageHits.length > 0 && (
            <div style={{ padding: '6px 14px 14px' }}>
              <div className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', color: 'var(--ink-4)', padding: '4px 10px' }}>PÁGINAS</div>
              {pageHits.map(p => (
                <button key={p.id} onClick={() => { route.go(p.id); onClose(); }} style={searchRow}>
                  <span style={{ flex: 1, textAlign: 'left' }}>
                    <span style={{ fontSize: 14 }}>{p.l}</span>
                    <span style={{ fontSize: 12, color: 'var(--ink-3)', marginLeft: 8 }}>{p.d}</span>
                  </span>
                  <span style={{ color: 'var(--ink-3)' }}>→</span>
                </button>
              ))}
            </div>
          )}
          {teamHits.length === 0 && pageHits.length === 0 && (
            <div style={{ padding: '36px 22px', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>Sin resultados para "{q}"</div>
          )}
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 18px', borderTop: '1px solid var(--line)', background: 'var(--bg-card)' }}>
          <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.1em' }}>↵ ABRIR · ESC CERRAR</span>
          <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.1em' }}>FLOW · BÚSQUEDA</span>
        </div>
      </div>
    </div>
  );
}

const searchRow = {
  width: '100%', display: 'flex', alignItems: 'center', gap: 12,
  padding: '10px 12px', borderRadius: 10, border: 'none',
  background: 'transparent', cursor: 'pointer', textAlign: 'left',
  color: 'var(--ink)', fontFamily: 'var(--sans)'
};

const iconBtn = {
  width: 40, height: 40, borderRadius: 12, border: '1px solid var(--line)',
  background: 'var(--bg-card)', color: 'var(--ink-2)', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative'
};

function Avatar({ initials, size = 32, color, photo }) {
  const colors = ['#e6e3da', '#d4d0c4', '#cfc9b8', '#bdb6a3', '#a8a89f'];
  const c = color || colors[(initials?.charCodeAt(0) || 0) % colors.length];
  if (photo) {
    return (
      <img src={photo} alt={initials || 'avatar'} width={size} height={size} style={{
        width: size, height: size, borderRadius: '50%',
        objectFit: 'cover', display: 'block',
        border: '1.5px solid var(--bg)', flexShrink: 0,
        background: c
      }} />
    );
  }
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', background: c,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--mono)', fontSize: size * 0.36, color: 'var(--ink)',
      border: '1.5px solid var(--bg)', flexShrink: 0
    }}>{initials}</div>
  );
}

// P. Ferrer demo portrait (used in TopNav and AI panel)
const PF_PHOTO = 'https://i.pravatar.cc/120?img=47';

// ============= INSIGHT CARD (subtle, minimal) =============
function InsightCard({ title, body, accent = 'green', onAction, actionLabel }) {
  const dot = accent === 'green' ? 'var(--green)' : accent === 'amber' ? 'var(--amber)' : 'var(--red)';
  return (
    <div style={{
      position: 'relative', padding: 22, borderRadius: 20,
      background: 'var(--bg-card)',
      border: '1px solid var(--line)',
      color: 'var(--ink)',
      overflow: 'hidden'
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ display: 'inline-block', width: 6, height: 6, minWidth: 6, minHeight: 6, flexShrink: 0, borderRadius: '50%', background: dot }}></span>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-3)', fontWeight: 500 }}>{title}</span>
        </div>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--ink-4)" strokeWidth="2"><path d="M7 17 17 7M9 7h8v8"/></svg>
      </div>
      <div style={{ fontFamily: 'var(--serif)', fontSize: 20, lineHeight: 1.3, color: 'var(--ink-2)', textWrap: 'pretty' }}>{body}</div>
      {onAction && (
        <button onClick={onAction} style={{
          marginTop: 14, padding: '7px 14px', borderRadius: 999,
          background: 'transparent', color: 'var(--ink)', border: '1px solid var(--line-2)',
          fontSize: 12, fontWeight: 500, cursor: 'pointer'
        }}>{actionLabel}</button>
      )}
    </div>
  );
}

// ============= AI ASSISTANT PANEL =============
function AIPanel() {
  const route = useRoute();
  const panelRef = useR(null);
  const [messages, setMessages] = useS([
    { who: 'user', name: 'P. Ferrer', text: 'Hey Flow, ¿podemos lanzar el sprint de Producto este martes?' },
    { who: 'ai', text: 'No recomendado. Producto · Madrid lleva 10 días con degradación sostenida (Recovery 58, HRV −12%). Aplazar al menos 7 días reduciría el riesgo de burnout.', chart: { from: 41, to: 62 } }
  ]);
  const [input, setInput] = useS('');
  const [busy, setBusy] = useS(false);

  // Close on click outside the panel + ESC
  useE(() => {
    const onDown = (e) => {
      if (!panelRef.current) return;
      if (panelRef.current.contains(e.target)) return;
      // Ignore clicks on the AI trigger buttons — they handle their own toggle
      const t = e.target.closest && e.target.closest('[data-ai-trigger], button');
      if (t) {
        if (t.dataset && t.dataset.aiTrigger) return;
        if (/Pregunta a Mihai/i.test(t.textContent || '')) return;
      }
      route.toggleAi();
    };
    const onKey = (e) => { if (e.key === 'Escape') route.toggleAi(); };
    // Use a microtask delay so the opening click doesn't immediately re-close it
    const id = setTimeout(() => {
      document.addEventListener('mousedown', onDown);
      document.addEventListener('keydown', onKey);
    }, 0);
    return () => {
      clearTimeout(id);
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, []);

  async function send() {
    if (!input.trim()) return;
    const q = input;
    setMessages(m => [...m, { who: 'user', name: 'P. Ferrer', text: q }]);
    setInput('');
    setBusy(true);
    try {
      const reply = await window.claude.complete({
        messages: [
          { role: 'user', content: `Eres Flow, un asistente de bienestar organizacional. Tienes datos agregados anónimos de 9 equipos con Flow Score 41-78. Responde en español, breve (2-3 frases máx), con tono ejecutivo. Si recomiendas algo, hazlo en una línea. Pregunta del CHRO: "${q}"` }
        ]
      });
      setMessages(m => [...m, { who: 'ai', text: reply || 'Sin respuesta.' }]);
    } catch (e) {
      setMessages(m => [...m, { who: 'ai', text: 'No puedo procesar esa consulta ahora.' }]);
    }
    setBusy(false);
  }

  return (
    <div ref={panelRef} style={{ width: 380, background: 'var(--bg-card)', borderLeft: '1px solid var(--line)', display: 'flex', flexDirection: 'column', flexShrink: 0, height: 'calc(100vh - 81px)' }}>
      <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 28, height: 28, borderRadius: 8, overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <img src="assets/mihai-chat-icon.png" alt="" width="28" height="28" style={{ display: 'block', width: '100%', height: '100%', objectFit: 'cover' }}/>
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Mihai · Asistente</div>
            <div className="mono" style={{ fontSize: 9, color: 'var(--ink-3)' }}>SEMÁNTICA NEURO · v0.4</div>
          </div>
        </div>
        <button onClick={() => route.toggleAi()} aria-label="Cerrar" style={{
          width: 30, height: 30, borderRadius: 8, border: '1px solid var(--line)',
          background: 'var(--bg)', color: 'var(--ink-2)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6l-12 12"/></svg>
        </button>
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {messages.map((m, i) => (
          <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: m.who === 'user' ? 'flex-end' : 'flex-start' }}>
            {m.who === 'user' ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span className="mono" style={{ fontSize: 9, color: 'var(--ink-4)' }}>{m.name}</span>
                <Avatar initials="PF" size={20} photo={PF_PHOTO} />
              </div>
            ) : (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ width: 20, height: 20, borderRadius: 5, overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <img src="assets/mihai-chat-icon.png" alt="" width="20" height="20" style={{ display: 'block', width: '100%', height: '100%', objectFit: 'cover' }}/>
                </div>
                <span className="mono" style={{ fontSize: 9, color: 'var(--ink-4)' }}>FLOW</span>
              </div>
            )}
            <div style={{
              maxWidth: '90%',
              padding: '10px 14px', borderRadius: 14,
              background: m.who === 'user' ? 'var(--bg)' : 'var(--ink)',
              color: m.who === 'user' ? 'var(--ink)' : '#fff',
              fontSize: 13, lineHeight: 1.5, textWrap: 'pretty'
            }}>{m.text}</div>
            {m.chart && (
              <div style={{ width: '100%', padding: 14, background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 12, marginTop: 4 }}>
                <div className="mono" style={{ fontSize: 9, letterSpacing: '0.1em', color: 'var(--ink-3)' }}>PROYECCIÓN FLOW · 14D</div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 10 }}>
                  <span style={{ fontFamily: 'var(--serif)', fontSize: 28, color: 'var(--red)' }}>{m.chart.from}</span>
                  <svg width="80" height="30" viewBox="0 0 80 30"><path d="M5 25 Q 40 5 75 8" stroke="var(--green)" strokeWidth="1.5" fill="none" strokeDasharray="3 3"/></svg>
                  <span style={{ fontFamily: 'var(--serif)', fontSize: 28, color: 'var(--green)' }}>{m.chart.to}</span>
                </div>
              </div>
            )}
          </div>
        ))}
        {busy && <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>· · ·</div>}
      </div>
      <div style={{ padding: 16, borderTop: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 10, flexWrap: 'wrap' }}>
          {['¿Qué equipo necesita más descanso?', 'Ventana ideal sprint', 'Riesgo burnout 30d'].map((q, i) => (
            <button key={i} onClick={() => setInput(q)} style={{
              padding: '5px 10px', borderRadius: 999, border: '1px solid var(--line)',
              background: 'var(--bg)', fontSize: 11, color: 'var(--ink-2)', cursor: 'pointer'
            }}>{q}</button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', padding: '8px 8px 8px 14px', background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 14 }}>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && send()}
            placeholder="Pregunta sobre el estado del equipo…"
            style={{ flex: 1, border: 'none', background: 'transparent', fontSize: 13, fontFamily: 'var(--sans)', outline: 'none', color: 'var(--ink)' }}
          />
          <button onClick={send} disabled={busy} style={{
            width: 32, height: 32, borderRadius: 10, border: 'none',
            background: 'var(--ink)', color: '#fff', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RouteCtx, useRoute, TEAMS, SEMAPHORE_GRADIENT, TopNav, Avatar, InsightCard, AIPanel, PF_PHOTO, SearchModal });
