/* global React */
const { useState, useEffect, createContext, useContext } = React;

// ─────────── App state / context ───────────
const DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "accentHue": 155,
  "lang": "EN",
  "intakeStyle": "hybrid",
  "density": "comfortable"
}/*EDITMODE-END*/;

const AppCtx = createContext(null);
const useApp = () => useContext(AppCtx);

const ACCENT_HUES = [
  { name: 'Forest', h: 155 },
  { name: 'Teal', h: 195 },
  { name: 'Indigo', h: 255 },
  { name: 'Aubergine', h: 320 },
  { name: 'Rust', h: 30 },
];

function useTweakState() {
  const [state, setState] = useState(() => {
    try {
      const saved = localStorage.getItem('govease_tweaks');
      if (saved) return { ...DEFAULTS, ...JSON.parse(saved) };
    } catch {}
    return DEFAULTS;
  });

  useEffect(() => {
    document.documentElement.dataset.theme = state.theme;
    document.documentElement.style.setProperty('--accent', `oklch(52% 0.11 ${state.accentHue})`);
    document.documentElement.style.setProperty('--accent-hover', `oklch(46% 0.11 ${state.accentHue})`);
    document.documentElement.style.setProperty('--accent-soft', `oklch(93% 0.04 ${state.accentHue})`);
    document.documentElement.style.setProperty('--accent-ink', `oklch(30% 0.08 ${state.accentHue})`);
    if (state.theme === 'dark') {
      document.documentElement.style.setProperty('--accent', `oklch(70% 0.13 ${state.accentHue})`);
      document.documentElement.style.setProperty('--accent-hover', `oklch(76% 0.14 ${state.accentHue})`);
      document.documentElement.style.setProperty('--accent-soft', `oklch(24% 0.05 ${state.accentHue})`);
      document.documentElement.style.setProperty('--accent-ink', `oklch(86% 0.10 ${state.accentHue})`);
    }
    try { localStorage.setItem('govease_tweaks', JSON.stringify(state)); } catch {}
  }, [state]);

  const set = (patch) => {
    setState(s => {
      const next = { ...s, ...patch };
      try {
        window.parent.postMessage({type: '__edit_mode_set_keys', edits: patch}, '*');
      } catch {}
      return next;
    });
  };
  return [state, set];
}

// ─────────── Top Bar ───────────
const TopBar = ({ persona, setPersona, onHome, tweaksOpen, setTweaksOpen }) => {
  const { tweaks, setTweaks } = useApp();
  return (
    <div className="topbar">
      <button className="brand brand-btn" onClick={onHome} title="Go to homepage">
        <span className="brand-mark">Ge</span>
        <span>GovEase</span>
        <span className="mono tiny" style={{color:'var(--ink-4)', marginLeft:4, letterSpacing:'.08em', textTransform:'uppercase'}}>DCW</span>
      </button>

      <div style={{marginLeft: 18}} className="persona-switch">
        {[['applicant','Applicant'],['reviewer','Reviewer'],['admin','Admin']].map(([k,label]) => (
          <button key={k} className={persona===k?'on':''} onClick={()=>setPersona(k)}>{label}</button>
        ))}
      </div>

      <div className="top-spacer"/>

      <div className="top-right">
        <button className="lang-pill" onClick={()=>setTweaks({lang: tweaks.lang==='EN'?'ES':'EN'})}>
          <span className={tweaks.lang==='EN'?'on':''}>EN</span>
          <span style={{color:'var(--ink-4)'}}>/</span>
          <span className={tweaks.lang==='ES'?'on':''}>ES</span>
        </button>
        <button className="icon-btn" onClick={()=>setTweaks({theme: tweaks.theme==='dark'?'light':'dark'})} title="Theme">
          <Icon name={tweaks.theme==='dark' ? 'sun' : 'moon'} size={16}/>
        </button>
        <button className="icon-btn" title="Help"><Icon name="info" size={16}/></button>
        <div style={{width:1, height:22, background:'var(--line)', margin:'0 4px'}}/>
        <div style={{display:'flex', alignItems:'center', gap:8, fontSize:12.5}}>
          {persona === 'applicant' && <>
            <div style={{width:26, height:26, borderRadius:'50%', background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center', fontSize:11, fontWeight:600}}>MR</div>
            <span style={{color:'var(--ink-2)'}}>Maria R.</span>
          </>}
          {persona === 'reviewer' && <>
            <div style={{width:26, height:26, borderRadius:'50%', background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center', fontSize:11, fontWeight:600}}>JD</div>
            <span style={{color:'var(--ink-2)'}}>J. Delacruz</span>
          </>}
          {persona === 'admin' && <>
            <div style={{width:26, height:26, borderRadius:'50%', background:'var(--ink)', color:'var(--bg)', display:'grid', placeItems:'center', fontSize:11, fontWeight:600}}>AK</div>
            <span style={{color:'var(--ink-2)'}}>A. Khan · Admin</span>
          </>}
        </div>
      </div>
    </div>
  );
};

// ─────────── Tweaks Panel ───────────
const TweaksPanel = ({ onClose }) => {
  const { tweaks, setTweaks } = useApp();
  return (
    <div className="tweaks-panel rise">
      <div className="tweaks-head">
        <h4>Tweaks</h4>
        <button className="icon-btn" onClick={onClose}><Icon name="x" size={14}/></button>
      </div>
      <div className="tweaks-body">
        <div className="tweak-row">
          <label>Theme</label>
          <div className="seg">
            <button className={tweaks.theme==='light'?'on':''} onClick={()=>setTweaks({theme:'light'})}>Light</button>
            <button className={tweaks.theme==='dark'?'on':''} onClick={()=>setTweaks({theme:'dark'})}>Dark</button>
          </div>
        </div>
        <div className="tweak-row">
          <label>Accent</label>
          <div className="hue-row">
            {ACCENT_HUES.map(h => (
              <div
                key={h.h}
                className={`hue-swatch ${tweaks.accentHue===h.h?'on':''}`}
                style={{background: `oklch(${tweaks.theme==='dark'?70:52}% ${tweaks.theme==='dark'?0.13:0.11} ${h.h})`}}
                onClick={()=>setTweaks({accentHue: h.h})}
                title={h.name}
              />
            ))}
          </div>
        </div>
        <div className="tweak-row">
          <label>Language</label>
          <div className="seg">
            <button className={tweaks.lang==='EN'?'on':''} onClick={()=>setTweaks({lang:'EN'})}>English</button>
            <button className={tweaks.lang==='ES'?'on':''} onClick={()=>setTweaks({lang:'ES'})}>Español</button>
          </div>
        </div>
        <div className="tweak-row">
          <label>Intake style</label>
          <div className="seg">
            <button className={tweaks.intakeStyle==='hybrid'?'on':''} onClick={()=>setTweaks({intakeStyle:'hybrid'})}>Hybrid</button>
            <button className={tweaks.intakeStyle==='card'?'on':''} onClick={()=>setTweaks({intakeStyle:'card'})}>Card</button>
          </div>
        </div>
        <div className="tweak-row">
          <label>Density</label>
          <div className="seg">
            <button className={tweaks.density==='comfortable'?'on':''} onClick={()=>setTweaks({density:'comfortable'})}>Comfortable</button>
            <button className={tweaks.density==='compact'?'on':''} onClick={()=>setTweaks({density:'compact'})}>Compact</button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ─────────── Save indicator ───────────
const SaveBar = ({ label }) => (
  <div className="save-bar">
    <span className="dot-g"/>
    <span>{label || 'Progress saved · resumes on any device'}</span>
  </div>
);

Object.assign(window, { AppCtx, useApp, useTweakState, TopBar, TweaksPanel, SaveBar });
