/* global React, ReactDOM, ExplainBlock, PanelA, PanelB, PanelC, PanelD, PageThumb */
const { useState: uS, useEffect: uE, useMemo: uM } = React;

function App() {
  const [option, setOption] = uS('B');
  const [globalTheme, setGlobalTheme] = uS('original');
  const [perModuleThemes, setPerModuleThemes] = uS({});
  const [focusedMod, setFocusedMod] = uS(null);
  const [customVars, setCustomVars] = uS({});
  const [customThemes, setCustomThemes] = uS([
    { id: 'halloween', name: 'NEXT Halloween', desc: 'Campanha Out·Nov', status: 'published', custom: true,
      vars: {...window.THEMES.original.vars, '--t-bg': '#1a0d05', '--t-surface': '#2a1408', '--t-primary': '#ff8a3c', '--t-primary-fg': '#1a0d05', '--t-accent': '#7a3aff', '--t-hero-a': '#3a1408', '--t-hero-b': '#ff8a3c', '--t-text': '#ffe8d4'},
      swatches: ['#1a0d05','#2a1408','#ff8a3c','#ffe8d4'] }
  ]);
  const [activeCustomId, setActiveCustomId] = uS('halloween');

  // when option changes, reset specifics
  uE(() => {
    if (option !== 'C') setFocusedMod(null);
    if (option === 'A') setGlobalTheme('original');
    if (option !== 'A') setCustomVars({});
  }, [option]);

  function applyCustomToAll(id) {
    const t = customThemes.find(x => x.id === id);
    if (!t) return;
    // inject into THEMES so it's picked up by select-mode rendering
    window.THEMES[id] = t;
    setGlobalTheme(id);
  }

  // For Option D, custom themes should be available in C-mode too
  uE(() => {
    customThemes.forEach(t => { window.THEMES[t.id] = t; });
  }, [customThemes]);

  const tabs = [
    { id: 'A', label: 'Color Picker', flag: 'no', flagText: 'Não recomendada' },
    { id: 'B', label: 'Temas Globais', flag: '', flagText: 'Fase 1' },
    { id: 'C', label: 'Tema por Módulo', flag: 'rec', flagText: 'Recomendada' },
    { id: 'D', label: 'Theme Builder', flag: 'req', flagText: 'Requer C' }
  ];

  const previewHeading = {
    A: 'Mesma página, mesmo módulo: tudo muda em conjunto',
    B: 'Selecione um tema — todas as páginas reagem em simultâneo',
    C: 'Cada módulo pode ter o seu tema · paleta diferente por secção',
    D: 'Crie um tema novo — fica disponível para usar por módulo'
  };

  const previewSub = {
    A: '4 páginas · ~20 cores manualmente definidas',
    B: '4 páginas · 1 escolha global',
    C: '4 páginas · ' + Object.values(perModuleThemes).filter(v => v && v !== globalTheme).length + ' módulos com override',
    D: customThemes.length + ' temas custom · ' + customThemes.filter(t => t.status === 'published').length + ' publicado(s)'
  };

  return (
    <div className={`app option-${option.toLowerCase()}`}>
      <header className="header">
        <div className="brand">
          <div className="brand-mark">N</div>
          <div className="brand-text">
            <div className="brand-name">Hotel Next — Sistema de Cores Configurável</div>
            <div className="brand-sub">proposta interativa · WYcreative · Abril 2026</div>
          </div>
        </div>
        <div className="header-meta">
          <span><b>4</b> opções</span>
          <span><b>4</b> paletas demo</span>
          <span><b>4</b> páginas</span>
          <span><b>~95</b> tokens / tema</span>
        </div>
      </header>

      <nav className="tabs-row">
        {tabs.map(t => (
          <button key={t.id} className={`tab ${option === t.id ? 'active' : ''}`} onClick={() => setOption(t.id)}>
            <div className="tab-letter">{t.id}</div>
            <span>{t.label}</span>
            {t.flag && <span className={`tab-flag ${t.flag}`}>{t.flagText}</span>}
          </button>
        ))}
      </nav>

      <main className="main">
        <aside className="control-pane">
          <ExplainBlock option={option} />

          {option === 'A' && <PanelA customVars={customVars} setCustomVars={setCustomVars} resetVars={() => setCustomVars({})} />}
          {option === 'B' && <PanelB globalTheme={globalTheme} setGlobalTheme={setGlobalTheme} />}
          {option === 'C' && <PanelC globalTheme={globalTheme} setGlobalTheme={setGlobalTheme}
                                     perModuleThemes={perModuleThemes} setPerModuleThemes={setPerModuleThemes}
                                     focusedMod={focusedMod} setFocusedMod={setFocusedMod} />}
          {option === 'D' && <PanelD customThemes={customThemes} setCustomThemes={setCustomThemes}
                                     activeCustomId={activeCustomId} setActiveCustomId={setActiveCustomId}
                                     applyCustom={applyCustomToAll}
                                     perModuleThemes={perModuleThemes} setPerModuleThemes={setPerModuleThemes} />}
        </aside>

        <section className="preview-pane">
          <div className="preview-head">
            <div>
              <h2>{previewHeading[option]}</h2>
              <div className="sub" style={{marginTop:4}}>{previewSub[option]}</div>
            </div>
            <div className="legend">
              {option === 'C' && (
                <span><i style={{background:'var(--app-accent)'}}></i>Módulo com tema próprio</span>
              )}
              {option === 'A' && (
                <span style={{color:'var(--app-warn)'}}><i style={{background:'var(--app-warn)'}}></i>Cada cor é manual</span>
              )}
            </div>
          </div>

          <div className="pages-grid">
            {window.PAGES.map(page => (
              <PageThumb key={page.id}
                         page={page}
                         globalTheme={globalTheme}
                         perModuleThemes={perModuleThemes}
                         customVars={option === 'A' ? customVars : null}
                         focusedMod={focusedMod}
                         optionMode={option} />
            ))}
          </div>
        </section>
      </main>
    </div>
  );
}

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