// brain-app.jsx — Shell principal du Brain TAKEYS (réactif)

const { useState: useStateApp, useEffect: useEffectApp, useCallback } = React;

const TWEAK_DEFAULTS = { density: 'comfortable', speedMul: 1, feedMode: 'timeline', showFeed: true };

function App() {
  const [activeId, setActiveId] = useStateApp('brain');
  const [filter, setFilter] = useStateApp('all');
  const [cmdOpen, setCmdOpen] = useStateApp(false);
  const [feedMode, setFeedMode] = useStateApp('timeline');
  const [theme, setTheme] = useStateApp(() => localStorage.getItem('brain-theme') || 'dark');
  const [tweaksOpen, setTweaksOpen] = useStateApp(false);
  const [tweaks, setTweak] = window.useTweaks ? window.useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, () => {}];
  const [now, setNow] = useStateApp(new Date());
  const [notifOpen, setNotifOpen] = useStateApp(false);

  // Re-render quand le store change (données live)
  const [, forceRender] = useStateApp(0);
  const [dismissedIds, setDismissedIds] = useStateApp(new Set());
  useEffectApp(() => {
    if (!window.BrainStore) return;
    return window.BrainStore.subscribe(() => forceRender(n => n + 1));
  }, []);

  // Lire depuis le store réactif
  const agents = window.BrainStore ? window.BrainStore.getAgents() : window.AGENTS;
  const feed = window.BrainStore ? window.BrainStore.getFeed() : window.FEED;
  const decisions = window.BrainStore ? window.BrainStore.getDecisions() : window.DECISIONS;
  const comms = window.BrainStore ? window.BrainStore.getComms() : window.COMMS;
  const lastRefresh = window.BrainStore ? window.BrainStore.getLastRefresh() : null;

  const handleApprove = (id) => {
    fetch(`/api/decisions/${id}`, { method: 'PATCH', headers: {'Content-Type':'application/json'}, body: JSON.stringify({action:'approve'}) });
    setDismissedIds(prev => new Set([...prev, id]));
  };
  const handleReject = (id) => {
    fetch(`/api/decisions/${id}`, { method: 'PATCH', headers: {'Content-Type':'application/json'}, body: JSON.stringify({action:'reject'}) });
    setDismissedIds(prev => new Set([...prev, id]));
  };

  useEffectApp(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('brain-theme', theme);
  }, [theme]);

  useEffectApp(() => {
    const id = setInterval(() => setNow(new Date()), 1000 * 30);
    return () => clearInterval(id);
  }, []);

  const agent = agents.find(a => a.id === activeId) || agents[0];

  const onCommand = (s) => {
    if (s.a === 'broadcast') return;
    setActiveId(s.a);
  };

  const greeting = (() => {
    const h = now.getHours();
    if (h < 12) return 'Bonjour';
    if (h < 18) return 'Bon après-midi';
    return 'Bonsoir';
  })();

  const visibleDecisions = decisions.filter(d => !dismissedIds.has(d.id));

  const totalTokens = agents.reduce((s, a) => s + a.tokens24h, 0);
  const totalCost = agents.reduce((s, a) => s + a.cost24h, 0);
  const totalActions = agents.reduce((s, a) => s + a.actions24h, 0);
  const decisionCount = visibleDecisions.length;

  return (
    <div className="brain">
      <Topbar theme={theme} setTheme={setTheme} setCmdOpen={setCmdOpen} setTweaksOpen={setTweaksOpen} now={now} lastRefresh={lastRefresh} notifOpen={notifOpen} setNotifOpen={setNotifOpen} />

      {notifOpen && (
        <div style={{position:'fixed',top:52,right:16,width:380,maxHeight:'70vh',background:'var(--surface)',border:'1px solid var(--border)',borderRadius:12,boxShadow:'0 8px 32px rgba(0,0,0,0.3)',zIndex:100,overflow:'auto',padding:0}}>
          <div style={{padding:'12px 16px',borderBottom:'1px solid var(--border)',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <span className="serif italic" style={{fontSize:16}}>Notifications</span>
            <button className="btn-mini" onClick={() => setNotifOpen(false)}>fermer</button>
          </div>
          <div style={{padding:8}}>
            {(window._notifications || []).length === 0 ? (
              <div style={{padding:16,textAlign:'center',opacity:0.5}}>Aucune notification</div>
            ) : (
              (window._notifications || []).map((n, i) => {
                const agentData = agents.find(a => a.id === n.agent);
                const color = agentData ? `oklch(0.62 0.08 ${agentData.hue})` : 'var(--muted)';
                return (
                  <div key={n.id || i} style={{padding:'10px 12px',borderBottom:'1px solid var(--border)',cursor:'pointer',opacity:n.read?0.5:1}} onClick={() => { setActiveId(n.agent); setNotifOpen(false); }}>
                    <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:4}}>
                      <span style={{width:8,height:8,borderRadius:'50%',background:color,display:'inline-block'}}/>
                      <span className="serif italic" style={{fontSize:13}}>{agentData?.name || n.agent}</span>
                      <span className="mono" style={{fontSize:10,opacity:0.5,marginLeft:'auto'}}>{n.at ? new Date(n.at).toLocaleTimeString('fr-FR',{hour:'2-digit',minute:'2-digit'}) : ''}</span>
                    </div>
                    <div style={{fontSize:13,fontWeight:n.read?400:500}}>{n.title}</div>
                    {n.text && <div style={{fontSize:12,opacity:0.7,marginTop:4,lineHeight:1.4}}>{n.text.slice(0,150)}</div>}
                  </div>
                );
              })
            )}
          </div>
        </div>
      )}

      <div className="brain-main">
        <AgentSidebar agents={agents} activeId={activeId} setActiveId={setActiveId} filter={filter} setFilter={setFilter}/>

        <div className="brain-center">
          <div className="brain-hero">
            <div>
              <h1 className="brain-hero-h serif">{greeting}, Charly. {decisionCount > 0 ? <><em className="italic">{decisionCount} décision{decisionCount !== 1 ? 's' : ''}</em> attendent.</> : <em className="italic">Tout roule.</em>}</h1>
              <div className="brain-hero-sub mono">
                7 AGENTS · {totalTokens > 0 ? `${(totalTokens / 1000).toFixed(0)} K TOKENS` : 'SYNC…'} / 24H · {totalCost > 0 ? `${totalCost.toFixed(2)} €` : '—'} · {totalActions} ACTIONS
                {lastRefresh && <span style={{marginLeft: 8, opacity: 0.5}}>· MAJ {new Date(lastRefresh).toLocaleTimeString('fr-FR', {hour:'2-digit',minute:'2-digit'})}</span>}
              </div>
            </div>
            <div className="brain-hero-actions">
              <button className="btn-pill" onClick={() => setFeedMode('timeline')}>
                <span className={feedMode === 'timeline' ? 'on' : ''}>timeline</span>
                <span className={feedMode === 'chat' ? 'on' : ''} onClick={(e) => { e.stopPropagation(); setFeedMode('chat'); }}>chat</span>
              </button>
              <button className="btn-pill ghost" onClick={() => setCmdOpen(true)}>
                <span>commande</span>
                <span className="kbd">⌘K</span>
              </button>
            </div>
          </div>

          <Constellation activeId={activeId} setActiveId={setActiveId} mode="constellation" speedMul={1}/>

          <div className="brain-decisions">
            {(decisionCount > 0
              ? visibleDecisions.slice(0, 3)
              : feed.length > 0
                ? [{agent:'brain', text:'Aucune décision en attente. Feed actif.'}]
                : [{agent:'brain', text:'Connexion aux sources…'}]
            ).map((d, i) => (
              <DecisionCard
                key={d.id || i}
                from={d.agent}
                agent={agents.find(a => a.id === d.agent) || agents[0]}
                text={d.text}
                onApprove={() => handleApprove(d.id)}
                onReject={() => handleReject(d.id)}
                setActiveId={setActiveId}
              />
            ))}
          </div>

          <div className="brain-feed">
            <div className="brain-feed-head">
              <div className="serif italic" style={{ fontSize: 18 }}>
                Activité en direct
                {feed.length > 0 && <span className="mono" style={{fontSize: 11, marginLeft: 8, opacity: 0.5}}>{feed.length} événements</span>}
              </div>
              <div className="brain-feed-tabs">
                <button className={feedMode === 'timeline' ? 'active' : ''} onClick={() => setFeedMode('timeline')}>timeline</button>
                <button className={feedMode === 'chat' ? 'active' : ''} onClick={() => setFeedMode('chat')}>chat</button>
              </div>
            </div>
            <ActivityFeed activeId={activeId} setActiveId={setActiveId} mode={feedMode}/>
          </div>
        </div>

        <Inspector agent={agent}/>
      </div>

      <CmdK open={cmdOpen} setOpen={setCmdOpen} onCommand={onCommand}/>

      {tweaksOpen && window.TweaksPanel && (
        <TweaksPanel title="Tweaks · Brain" onClose={() => setTweaksOpen(false)}>
          <window.TweakSection title="Apparence">
            <window.TweakRadio label="Thème" value={theme} options={[['dark','Dark'],['light','Light']]} onChange={setTheme}/>
          </window.TweakSection>
          <window.TweakSection title="Animation">
            <window.TweakSlider label="Vitesse comms" value={tweaks.speedMul} min={0.4} max={2.4} step={0.2} onChange={(v) => setTweak('speedMul', v)}/>
          </window.TweakSection>
        </TweaksPanel>
      )}
    </div>
  );
}

function Topbar({ theme, setTheme, setCmdOpen, setTweaksOpen, now, lastRefresh, notifOpen, setNotifOpen }) {
  const time = now.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
  const date = now.toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long' });
  return (
    <header className="topbar">
      <div className="topbar-l">
        <a href="/" className="topbar-brand">
          <img src={theme === 'dark' ? '/assets/logo-nav-white.png' : '/assets/logo-nav-dark.png'} alt="TAKEYS" style={{height: 22, marginRight: 8}} />
          <span className="brand-section mono">/ BRAIN</span>
        </a>
        <span className="topbar-sep">·</span>
        <span className="topbar-meta mono">{date.toUpperCase()} · {time}</span>
        {lastRefresh && <span className="topbar-meta mono" style={{marginLeft:8, color:'var(--success)'}}>● LIVE</span>}
        {window._bridgeStatus === 'ok'
          ? <span className="topbar-meta mono" style={{color:'var(--success)'}}>● BRIDGE</span>
          : window._bridgeStatus === 'down'
            ? <span className="topbar-meta mono" style={{color:'var(--danger)'}}>● BRIDGE OFF</span>
            : null
        }
      </div>
      <div className="topbar-r">
        <button className="topbar-btn" onClick={() => setCmdOpen(true)}>
          <span>commande</span>
          <span className="kbd">⌘K</span>
        </button>
        <button className="topbar-btn icon" onClick={() => setNotifOpen(o => !o)} title="Notifications" style={{position:'relative'}}>
          🔔
          {(window._unreadCount || 0) > 0 && (
            <span style={{position:'absolute',top:2,right:2,background:'var(--danger)',color:'#fff',borderRadius:'50%',width:16,height:16,fontSize:10,display:'flex',alignItems:'center',justifyContent:'center'}}>{window._unreadCount}</span>
          )}
        </button>
        <button className="topbar-btn icon" onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')} title="Thème">
          {theme === 'dark' ? '☾' : '☀'}
        </button>
        <button className="topbar-btn icon" onClick={() => setTweaksOpen(true)} title="Tweaks">⚙</button>
        <div className="topbar-user" onClick={() => setCmdOpen(true)} style={{cursor:'pointer'}} title="⌘K — Donner un ordre">
          <div className="topbar-user-av">C</div>
        </div>
      </div>
    </header>
  );
}

function DecisionCard({ agent, text, onApprove, onReject, setActiveId }) {
  if (!agent) return null;
  const color = `oklch(0.62 0.08 ${agent.hue})`;
  return (
    <div className="dec-card" onClick={() => setActiveId(agent.id)}>
      <div className="dec-card-head">
        <span className="dec-card-glyph" style={{ background: `oklch(0.62 0.08 ${agent.hue} / 0.18)`, borderColor: color, color }}>
          {agent.id === 'brain' ? '◉' : agent.name[0]}
        </span>
        <div>
          <div className="serif italic dec-card-name">{agent.name}</div>
          <div className="mono dec-card-role">{agent.role.split(' · ')[0].toUpperCase()}</div>
        </div>
        <span className="dec-card-tag">? demande</span>
      </div>
      <div className="dec-card-text">{text}</div>
      <div className="dec-card-actions">
        <button className="btn-mini" onClick={(e) => { e.stopPropagation(); onReject(); }}>refuser</button>
        <button className="btn-mini" onClick={(e) => { e.stopPropagation(); setActiveId(agent.id); }}>discuter</button>
        <button className="btn-mini primary" onClick={(e) => { e.stopPropagation(); onApprove(); }}>approuver</button>
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
