// ---------- App entry: landing / admin + Tweaks panel ----------

window.__tweaks = window.__tweaks || {
  view: 'landing',       // 'landing' | 'admin'
  role: 'boss',          // boss | production_manager | accountant | employee
  theme: 'dark',         // dark | light | sand — persisted as gh-theme
  accent: 'terracotta',
  lang: 'en',
  heroVariant: 'editorial',
  showGrain: true,
  fontSize: 'lg',        // sm | md | lg | xl | 2xl | 3xl | 4xl — synced with localStorage gh-font-size
};

/** Apply appearance theme (dark / light / sand), persist, sync body classes + tweak-change */
window.__applyGhTheme = function (name) {
  var allowed = { dark: 1, light: 1, sand: 1 };
  var n = allowed[name] ? name : 'dark';
  window.__tweaks = window.__tweaks || {};
  window.__tweaks.theme = n;
  document.body.classList.toggle('theme-light', n === 'light');
  document.body.classList.toggle('theme-sand', n === 'sand');
  try { localStorage.setItem('gh-theme', n); } catch (e) { /* no-op */ }
  window.dispatchEvent(new Event('tweak-change'));
};

const __FONT_SIZES = new Set(['sm', 'md', 'lg', 'xl', '2xl', '3xl', '4xl']);
window.__setTextSize = function (name) {
  if (!__FONT_SIZES.has(name)) return;
  try { localStorage.setItem('gh-font-size', name); } catch (e) { /* no-op */ }
  document.documentElement.setAttribute('data-font-size', name);
  if (window.__tweaks) window.__tweaks.fontSize = name;
  try {
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { fontSize: name } }, '*');
  } catch (e) { /* no-op */ }
  window.dispatchEvent(new Event('tweak-change'));
};

// Accent token setter
window.__setAccent = function(name) {
  const map = {
    terracotta: ['#C0603A','#D97B52','rgba(192,96,58,0.15)','rgba(192,96,58,0.28)'],
    gold:       ['#C9962A','#E6B84A','rgba(201,150,42,0.16)','rgba(201,150,42,0.30)'],
    sahel:      ['#A67C3D','#C69A5A','rgba(166,124,61,0.16)','rgba(166,124,61,0.30)'],
    teal:       ['#3D7B7B','#5A9B9B','rgba(61,123,123,0.16)','rgba(61,123,123,0.30)'],
    midnight:   ['#2D4A6B','#4A6F96','rgba(45,74,107,0.16)','rgba(45,74,107,0.30)'],
  };
  const [a, al, ad, ab] = map[name] || map.terracotta;
  const s = document.documentElement.style;
  s.setProperty('--accent', a);
  s.setProperty('--accent-light', al);
  s.setProperty('--accent-dim', ad);
  s.setProperty('--accent-border', ab);
  if (window.__tweaks) window.__tweaks.accent = name;
  window.dispatchEvent(new Event('tweak-change'));
};

function App() {
  const [view, setView] = React.useState(window.__tweaks.view);
  const [role, setRole] = React.useState(window.__tweaks.role);
  const [adminSession, setAdminSession] = React.useState(() => {
    const read = typeof window !== 'undefined' && typeof window.readAdminSessionRaw === 'function'
      ? window.readAdminSessionRaw
      : null;
    return read ? read() : null;
  });
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [editAvail, setEditAvail] = React.useState(false);

  React.useEffect(() => {
    const h = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', h);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    setEditAvail(true);
    return () => window.removeEventListener('message', h);
  }, []);

  React.useEffect(() => {
    const onT = () => {
      setView(window.__tweaks.view);
      setRole(window.__tweaks.role);
    };
    window.addEventListener('tweak-change', onT);
    return () => window.removeEventListener('tweak-change', onT);
  }, []);

  React.useEffect(() => {
    if (adminSession && window.__tweaks) window.__tweaks.role = adminSession.role;
  }, [adminSession]);

  const exitAdmin = () => {
    try {
      sessionStorage.removeItem('gh_session_v1');
    } catch (e) { /* */ }
    setAdminSession(null);
    window.__tweaks.view = 'landing';
    window.dispatchEvent(new Event('tweak-change'));
  };

  const loginAdmin = () => {
    window.__tweaks.view = 'admin';
    window.dispatchEvent(new Event('tweak-change'));
  };

  const onAdminLoginSuccess = (sess) => {
    setAdminSession(sess);
    setRole(sess.role);
    if (window.__tweaks) window.__tweaks.role = sess.role;
  };

  return (
    <>
      {view === 'landing'
        ? <LandingPage onEnterAdmin={loginAdmin}/>
        : (adminSession ? (
            <AdminShell
              currentRole={adminSession.role}
              sessionEmployeeId={adminSession.employeeId}
              onLogout={exitAdmin}
              onExit={exitAdmin}
            />
          ) : (
            <AdminLogin onSuccess={onAdminLoginSuccess} />
          ))
      }
      <TweaksPanel open={tweaksOpen} onClose={()=>setTweaksOpen(false)}/>
    </>
  );
}

function TweaksPanel({ open, onClose }) {
  const [, setTick] = React.useState(0);
  const refresh = () => setTick(x => x+1);
  const set = (k, v) => {
    if (k === 'theme') {
      window.__applyGhTheme(v);
      try {
        window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
      } catch {}
      refresh();
      return;
    }
    window.__tweaks[k] = v;
    if (k === 'accent') window.__setAccent(v);
    if (k === 'fontSize' && window.__setTextSize) window.__setTextSize(v);
    if (k === 'lang' && window.setLang) window.setLang(v);
    window.dispatchEvent(new Event('tweak-change'));
    // persist via host
    try {
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
    } catch {}
    refresh();
  };

  if (!open) return null;
  const t = window.__tweaks;
  let staffSessionLocksRole = false;
  try {
    staffSessionLocksRole = !!sessionStorage.getItem('gh_session_v1');
  } catch (e) { /* */ }

  const SectionTitle = ({ children }) => (
    <div style={{fontSize:10,letterSpacing:'0.18em',textTransform:'uppercase',color:'var(--text-dim)',marginBottom:8,marginTop:18,fontFamily:'JetBrains Mono'}}>{children}</div>
  );

  return (
    <aside id="tweaks-panel" className="open" style={{display:'block'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
        <div>
          <div style={{fontSize:14,fontWeight:600,display:'flex',alignItems:'center',gap:8}}>
            <span style={{width:7,height:7,borderRadius:'50%',background:'var(--accent)',animation:'pulseDot 2s infinite'}}/> Tweaks
          </div>
          <div style={{fontSize:10,color:'var(--text-dim)',marginTop:2,fontFamily:'JetBrains Mono',textTransform:'uppercase',letterSpacing:'0.12em'}}>Live preview</div>
        </div>
        <button onClick={onClose} style={{color:'var(--text-dim)',padding:4}}><Icon.X size={16}/></button>
      </div>

      <SectionTitle>View</SectionTitle>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:6}}>
        {[['landing','Landing'],['admin','Admin']].map(([v,l]) => (
          <button key={v} onClick={()=>set('view', v)} style={{padding:'8px 10px',borderRadius:8,fontSize:12,border:'1px solid '+(t.view===v?'var(--accent)':'var(--border)'),background:t.view===v?'var(--accent-dim)':'var(--card2)',color:t.view===v?'var(--accent)':'var(--text)'}}>{l}</button>
        ))}
      </div>

      {t.view === 'admin' && !staffSessionLocksRole && (
        <>
          <SectionTitle>Role</SectionTitle>
          <div style={{display:'flex',flexDirection:'column',gap:4}}>
            {[['boss','Boss · full access'],['production_manager','Production manager'],['accountant','Accountant'],['employee','Employee · view only']].map(([v,l]) => (
              <button key={v} onClick={()=>set('role', v)} style={{padding:'8px 10px',borderRadius:8,fontSize:12,textAlign:'start',border:'1px solid '+(t.role===v?'var(--accent)':'var(--border)'),background:t.role===v?'var(--accent-dim)':'var(--card2)',color:t.role===v?'var(--accent)':'var(--text)'}}>{l}</button>
            ))}
          </div>
        </>
      )}
      {t.view === 'admin' && staffSessionLocksRole && (
        <p style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 8 }}>Role is set by your staff login. Log out from the top bar to use preview roles.</p>
      )}

      <SectionTitle>Theme</SectionTitle>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:6}}>
        {['dark','light'].map(v => (
          <button key={v} onClick={()=>set('theme', v)} style={{padding:'8px 10px',borderRadius:8,fontSize:12,textTransform:'capitalize',border:'1px solid '+(t.theme===v?'var(--accent)':'var(--border)'),background:t.theme===v?'var(--accent-dim)':'var(--card2)',color:t.theme===v?'var(--accent)':'var(--text)'}}>{v}</button>
        ))}
      </div>

      <SectionTitle>Accent</SectionTitle>
      <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
        {[['terracotta','#C0603A'],['gold','#C9962A'],['sahel','#A67C3D'],['teal','#3D7B7B'],['midnight','#2D4A6B']].map(([n,c]) => (
          <button key={n} title={n} onClick={()=>set('accent', n)} style={{width:32,height:32,borderRadius:8,background:c,border: t.accent===n ? '2px solid var(--text)' : '2px solid transparent'}}/>
        ))}
      </div>

      <SectionTitle>Language</SectionTitle>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:6}}>
        {[['en','EN'],['fr','FR'],['ar','AR']].map(([v,l]) => (
          <button key={v} onClick={()=>set('lang', v)} style={{padding:'8px 10px',borderRadius:8,fontSize:12,border:'1px solid '+(t.lang===v?'var(--accent)':'var(--border)'),background:t.lang===v?'var(--accent-dim)':'var(--card2)',color:t.lang===v?'var(--accent)':'var(--text)'}}>{l}</button>
        ))}
      </div>

      <SectionTitle>Text size</SectionTitle>
      <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:6}}>
        {[
          ['sm', 'S'], ['md', 'M'], ['lg', 'L'], ['xl', 'XL'], ['2xl', '2X'], ['3xl', '3X'], ['4xl', 'Max'],
        ].map(([v, label]) => (
          <button
            key={v}
            onClick={() => { if (window.__setTextSize) { window.__setTextSize(v); } refresh(); }}
            style={{
              padding: '8px 6px', borderRadius: 8, fontSize: 12, fontWeight: 600, fontFamily: 'JetBrains Mono',
              border: '1px solid ' + (t.fontSize === v ? 'var(--accent)' : 'var(--border)'),
              background: t.fontSize === v ? 'var(--accent-dim)' : 'var(--card2)',
              color: t.fontSize === v ? 'var(--accent)' : 'var(--text)',
            }}
          >
            {label}
          </button>
        ))}
      </div>
      <p style={{ fontSize: 10, color: 'var(--text-dim)', lineHeight: 1.4, marginTop: 4 }}>
        Uses the same setting as the public site. Saved in this browser.
      </p>

      {t.view === 'landing' && (
        <>
          <SectionTitle>Hero variant</SectionTitle>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:6}}>
            {[['editorial','Editorial'],['split','Split image'],['centered','Centered'],['archive','Archive']].map(([v,l]) => (
              <button key={v} onClick={()=>set('heroVariant', v)} style={{padding:'8px 10px',borderRadius:8,fontSize:12,border:'1px solid '+(t.heroVariant===v?'var(--accent)':'var(--border)'),background:t.heroVariant===v?'var(--accent-dim)':'var(--card2)',color:t.heroVariant===v?'var(--accent)':'var(--text)'}}>{l}</button>
            ))}
          </div>
        </>
      )}

      <SectionTitle>Effects</SectionTitle>
      <label style={{display:'flex',alignItems:'center',gap:8,padding:'8px 10px',background:'var(--card2)',borderRadius:8,cursor:'pointer',fontSize:12}}>
        <input type="checkbox" checked={t.showGrain} onChange={e=>{
          set('showGrain', e.target.checked);
          document.body.style.setProperty('--grain-display', e.target.checked ? 'block' : 'none');
        }}/> Film grain overlay
      </label>
    </aside>
  );
}

// Boot
(function boot() {
  var saved; try { saved = localStorage.getItem('gh-font-size'); } catch (e) { saved = null; }
  if (saved && __FONT_SIZES.has(saved) && window.__tweaks) window.__tweaks.fontSize = saved;
  if (window.__setTextSize) window.__setTextSize((window.__tweaks && window.__tweaks.fontSize) || 'lg');
  var savedTheme = 'dark';
  try {
    var gt = localStorage.getItem('gh-theme');
    if (gt === 'dark' || gt === 'light' || gt === 'sand') savedTheme = gt;
  } catch (e) { /* no-op */ }
  window.__applyGhTheme(savedTheme);
  if (window.__tweaks.accent) window.__setAccent(window.__tweaks.accent);
  if (window.__tweaks.lang && window.setLang) window.setLang(window.__tweaks.lang);
  window.__lang = window.__tweaks.lang;

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

