/* ============================================================
   FIFA EDGE — app root + Tweaks
   ============================================================ */

const { useState: useS, useEffect: useE } = React;

const ACCENTS = [
  { id:'green',  color:'oklch(0.78 0.16 155)', letter:'G' },
  { id:'amber',  color:'oklch(0.80 0.14 75)',  letter:'A' },
  { id:'cyan',   color:'oklch(0.80 0.12 210)', letter:'C' },
  { id:'violet', color:'oklch(0.72 0.17 300)', letter:'V' },
];

function TweaksPanel({ tweaks, set, editMode, onClose }) {
  if (!editMode) return null;
  return (
    <div className="tweaks-panel">
      <h4>Tweaks <button className="iconbtn" style={{width:22, height:22}} onClick={onClose}>×</button></h4>
      <div className="tweak">
        <span className="lbl">Acento de cor</span>
        <div className="swatches">
          {ACCENTS.map(a => (
            <div key={a.id}
                 className={`sw ${tweaks.accent===a.id?'active':''}`}
                 style={{background:a.color}}
                 onClick={()=>set('accent', a.id)}
                 title={a.id}>{a.letter}</div>
          ))}
        </div>
      </div>
      <div className="tweak">
        <span className="lbl">Densidade</span>
        <div className="seg">
          {['compact','comfortable','spacious'].map(d => (
            <button key={d} className={tweaks.density===d?'active':''} onClick={()=>set('density', d)}>
              {d==='compact'?'Compacto':d==='comfortable'?'Padrão':'Espaçoso'}
            </button>
          ))}
        </div>
      </div>
      <div className="tweak">
        <span className="lbl">Mostrar coluna EV</span>
        <div className="seg" style={{gridTemplateColumns:'1fr 1fr'}}>
          <button className={tweaks.showEv?'active':''} onClick={()=>set('showEv', true)}>Sim</button>
          <button className={!tweaks.showEv?'active':''} onClick={()=>set('showEv', false)}>Não</button>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [section, setSection] = useS(() => {
    const s = localStorage.getItem('fe.section') || 'today';
    return s === 'settings' ? 'today' : s;
  });
  const [h2hId, setH2hId] = useS(null);
  const [tweaks, setTweaks] = useS(window.TWEAKS);
  const [editMode, setEditMode] = useS(false);

  useE(() => localStorage.setItem('fe.section', section), [section]);

  // expose opener for match rows
  React.useEffect(() => {
    window.openH2H = (id) => setH2hId(id);
  }, []);

  useE(() => {
    document.documentElement.setAttribute('data-accent', tweaks.accent);
    document.documentElement.setAttribute('data-density', tweaks.density);
  }, [tweaks]);

  // Tweaks protocol
  useE(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode')   setEditMode(true);
      if (e.data.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const setTweak = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  };

  if (h2hId) {
    return (
      <div className="app" data-screen-label="h2h">
        <Sidebar current={section} onNav={(s)=>{ setH2hId(null); setSection(s); }} />
        <div className="main">
          <Topbar section={section} />
          <div className="content">
            <H2HDetail matchId={h2hId} onBack={() => setH2hId(null)} />
          </div>
        </div>
        <TweaksPanel tweaks={tweaks} set={setTweak} editMode={editMode} onClose={() => setEditMode(false)} />
      </div>
    );
  }

  const viewMap = {
    today: <TodayView showEv={tweaks.showEv} />,
    live: <LiveView />,
    signals: <SignalsView />,
    elo: <EloView />,
    stats: <StatsView />,
    perf: <PerfView />,
  };

  return (
    <div className="app" data-screen-label={section}>
      <Sidebar current={section} onNav={setSection} />
      <div className="main">
        <Topbar section={section} />
        <div className="content">
          {viewMap[section]}
        </div>
      </div>
      <TweaksPanel tweaks={tweaks} set={setTweak} editMode={editMode} onClose={() => setEditMode(false)} />
    </div>
  );
}

const __feRoot = ReactDOM.createRoot(document.getElementById('root'));
const __feMount = () => __feRoot.render(<App />);
(window.__FIFA_READY__ || Promise.resolve()).finally(__feMount);
window.addEventListener('fifa:data', __feMount); // re-render on future refreshes
