// portal-app.jsx — Employee portal shell: browser frame → login → sidebar app.

const PORTAL_PALETTE = ['#E55B13', '#1D6FB8', '#137C50', '#5B3FB8', '#0F172A'];
function portalTheme(accent) {
  const root = document.documentElement;
  root.style.setProperty('--accent', accent);
  const h = accent.replace('#', '');
  const r = parseInt(h.slice(0,2),16), g = parseInt(h.slice(2,4),16), b = parseInt(h.slice(4,6),16);
  root.style.setProperty('--accent-deep', `#${Math.round(r*0.78).toString(16).padStart(2,'0')}${Math.round(g*0.78).toString(16).padStart(2,'0')}${Math.round(b*0.78).toString(16).padStart(2,'0')}`);
  root.style.setProperty('--accent-soft', `#${Math.round(r+(255-r)*0.86).toString(16).padStart(2,'0')}${Math.round(g+(255-g)*0.86).toString(16).padStart(2,'0')}${Math.round(b+(255-b)*0.86).toString(16).padStart(2,'0')}`);
}

function PortalApp() {
  const [tweaks, setTweak] = useTweaks(window.__TWEAK_DEFAULTS);
  useEffect(() => {
    window.__currentTweaks = tweaks;
    window.dispatchEvent(new Event('tweaks-changed'));
    portalTheme(tweaks.accent);
    document.title = `${tweaks.companyName} — Employee Portal`;
  }, [tweaks]);
  useEffect(() => { portalTheme(tweaks.accent); }, []);

  return (
    <PortalProvider>
      <div style={{ minHeight: '100vh', width: '100%', background: 'radial-gradient(circle at 30% 10%, #20262e 0%, #0a0d11 60%, #06080b 100%)', display: 'grid', placeItems: 'center', padding: 16 }}>
        <PortalFrame><PortalGate /></PortalFrame>
      </div>
      <TweaksPanel title="Tweaks">
        <TweakSection label="White-label">
          <TweakText label="Company name" value={tweaks.companyName} onChange={v => setTweak('companyName', v)} />
          <TweakText label="Tagline" value={tweaks.tagline} onChange={v => setTweak('tagline', v)} />
        </TweakSection>
        <TweakSection label="Theme">
          <TweakColor label="Accent" value={tweaks.accent} options={PORTAL_PALETTE} onChange={v => setTweak('accent', v)} />
        </TweakSection>
      </TweaksPanel>
    </PortalProvider>
  );
}

// Browser-window frame, scales to fit
function PortalFrame({ children }) {
  const W = 1440, H = 1000;
  const [scale, setScale] = useState(1);
  useEffect(() => {
    const compute = () => setScale(Math.min((window.innerWidth - 32) / W, (window.innerHeight - 32) / H, 1));
    compute(); window.addEventListener('resize', compute); return () => window.removeEventListener('resize', compute);
  }, []);
  return (
    <div style={{ width: W * scale, height: H * scale, borderRadius: 14, overflow: 'hidden', boxShadow: '0 50px 100px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.05)' }}>
      <div style={{ transform: `scale(${scale})`, transformOrigin: 'top left', width: W, height: H, display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
        <div style={{ height: 38, flexShrink: 0, background: '#E9EAEC', borderBottom: '1px solid #D4D6DA', display: 'flex', alignItems: 'center', padding: '0 14px', gap: 14 }}>
          <div style={{ display: 'flex', gap: 7 }}>
            {['#FF5F57', '#FEBC2E', '#28C840'].map(c => <span key={c} style={{ width: 12, height: 12, borderRadius: 6, background: c }} />)}
          </div>
          <div style={{ flex: 1, maxWidth: 460, margin: '0 auto', padding: '5px 14px', borderRadius: 6, background: '#fff', border: '1px solid #D4D6DA', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-2)', textAlign: 'center' }}>
            🔒 my.railflagspro.com
          </div>
          <div style={{ width: 30 }} />
        </div>
        <div style={{ flex: 1, display: 'flex', overflow: 'hidden', position: 'relative' }}>{children}</div>
      </div>
    </div>
  );
}

function PortalGate() {
  const { authed } = usePortal();
  return authed ? <PortalShell /> : <PortalLogin />;
}

// ── Login ────────────────────────────────────────────────────
function PortalLogin() {
  const { setAuthed, me } = usePortal();
  const { tweaks } = useTweakValues();
  const [email, setEmail] = useState('mhale@demo-rwic.com');
  const [pw, setPw] = useState('demo123');
  const [err, setErr] = useState('');
  const [loading, setLoading] = useState(false);
  const submit = async () => {
    setErr('');
    setLoading(true);
    try {
      let res;
      if (RFP.loginAsync) {
        res = await RFP.loginAsync(email, pw, 'portal');
      } else {
        res = RFP.login(email, pw, 'portal');
      }
      if (res.ok) setAuthed(true);
      else setErr(res.error);
    } catch (e) {
      setErr(e.message || 'Login failed.');
    } finally {
      setLoading(false);
    }
  };
  return (
    <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1.1fr 0.9fr' }}>
      {/* Left brand panel */}
      <div style={{ background: 'linear-gradient(160deg, #0F172A 0%, #1a2536 100%)', color: '#fff', padding: '56px 56px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -80, right: -80, width: 300, height: 300, borderRadius: '50%', background: 'var(--accent)', opacity: 0.18, filter: 'blur(10px)' }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, position: 'relative' }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, background: '#0F172A', border: '1px solid rgba(255,255,255,0.15)', display: 'grid', placeItems: 'center', fontWeight: 700, position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, background: 'var(--accent)', clipPath: 'polygon(0 100%, 100% 100%, 100% 58%, 0 90%)' }} />
            <span style={{ position: 'relative', zIndex: 1 }}>{(tweaks.companyName||'RF').split(/\s+/).map(w=>w[0]).join('').slice(0,2).toUpperCase()}</span>
          </div>
          <div style={{ fontWeight: 700, fontSize: 17 }}>{tweaks.companyName}</div>
        </div>
        <div style={{ position: 'relative' }}>
          <div style={{ fontSize: 30, fontWeight: 700, letterSpacing: -0.8, lineHeight: 1.15 }}>Your pay, time,<br />and documents.</div>
          <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.65)', marginTop: 12, lineHeight: 1.6, maxWidth: 320 }}>Pay stubs, W-2s, time-off, reimbursements, certifications, and signed documents — all in one place.</div>
        </div>
        <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.4)', position: 'relative' }} className="mono">{tweaks.tagline} · v1.0</div>
      </div>

      {/* Right form */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 48 }}>
        <div style={{ width: '100%', maxWidth: 340 }}>
          <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: -0.4 }}>Sign in</div>
          <div style={{ fontSize: 13.5, color: 'var(--muted)', marginTop: 4, marginBottom: 24 }}>Use your company email and password.</div>
          <PField label="Work email"><input value={email} onChange={e => setEmail(e.target.value)} onKeyDown={e => e.key === 'Enter' && submit()} style={pInputStyle} /></PField>
          <PField label="Password"><input type="password" value={pw} onChange={e => setPw(e.target.value)} onKeyDown={e => e.key === 'Enter' && submit()} style={pInputStyle} /></PField>
          {err && <div style={{ background: 'var(--bad-soft)', color: 'var(--bad)', padding: '8px 12px', borderRadius: 8, fontSize: 12.5, marginBottom: 14 }}>{err}</div>}
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--muted)', margin: '4px 0 18px' }}>
            <input type="checkbox" defaultChecked style={{ width: 15, height: 15 }} /> Remember this device
          </label>
          <Button variant="primary" size="lg" style={{ width: '100%', opacity: loading ? 0.7 : 1 }} onClick={submit} disabled={loading}>{loading ? 'Signing in…' : 'Sign in'}</Button>
          <div style={{ textAlign: 'center', marginTop: 16, fontSize: 12.5, color: 'var(--muted)' }}>Forgot password? · Contact HR</div>
          <div style={{ textAlign: 'center', marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--line)', fontSize: 12, color: 'var(--muted-2)' }}>
            Demo — mhale@demo-rwic.com · password <span className="mono" style={{ color: 'var(--accent-deep)' }}>demo123</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Shell ────────────────────────────────────────────────────
function PortalShell() {
  const { me, setAuthed, inbox, certs, toasts, activeDoc, setActiveDoc } = usePortal();
  const [screen, setScreen] = useState('home');
  const { tweaks } = useTweakValues();
  const actionDocs = inbox.filter(d => d.status === 'action-required').length;
  const certIssues = certs.filter(c => c.status !== 'current').length;

  const nav = [
    { id: 'home', label: 'Home', icon: <IconHome size={18} /> },
    { id: 'pay', label: 'Pay & documents', icon: <IconDollar size={18} /> },
    { id: 'timecards', label: 'Timecards', icon: <IconClock size={18} /> },
    { id: 'pto', label: 'Time off', icon: <IconClipboard size={18} /> },
    { id: 'reimb', label: 'Reimbursements', icon: <IconDollar size={18} /> },
    { id: 'certs', label: 'Certifications', icon: <IconShield size={18} />, badge: certIssues },
    { id: 'inbox', label: 'Documents', icon: <IconBell size={18} />, badge: actionDocs },
    { id: 'profile', label: 'My profile', icon: <IconUser size={18} /> },
  ];

  return (
    <>
      {/* Sidebar */}
      <aside style={{ width: 230, flexShrink: 0, background: '#0E1622', color: 'rgba(255,255,255,0.85)', display: 'flex', flexDirection: 'column', padding: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 6px 18px' }}>
          <div style={{ width: 34, height: 34, borderRadius: 9, background: '#0F172A', border: '1px solid rgba(255,255,255,0.1)', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12, position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, background: 'var(--accent)', clipPath: 'polygon(0 100%, 100% 100%, 100% 58%, 0 90%)' }} />
            <span style={{ position: 'relative', zIndex: 1 }}>{(tweaks.companyName||'RF').split(/\s+/).map(w=>w[0]).join('').slice(0,2).toUpperCase()}</span>
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 13.5, color: '#fff' }}>{tweaks.companyName}</div>
            <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.5)' }}>{tweaks.tagline}</div>
          </div>
        </div>

        <nav style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          {nav.map(n => {
            const on = screen === n.id;
            return (
              <button key={n.id} onClick={() => setScreen(n.id)} style={{
                display: 'flex', alignItems: 'center', gap: 11, padding: '10px 12px',
                background: on ? 'rgba(255,255,255,0.08)' : 'transparent',
                border: 'none',
                borderLeft: on ? '3px solid var(--accent)' : '3px solid transparent',
                borderRadius: 8, cursor: 'pointer', textAlign: 'left',
                color: on ? '#fff' : 'rgba(255,255,255,0.65)',
              }}>
                <span style={{ color: on ? 'var(--accent)' : 'rgba(255,255,255,0.5)' }}>{n.icon}</span>
                <span style={{ flex: 1, fontSize: 13.5, fontWeight: on ? 600 : 500 }}>{n.label}</span>
                {n.badge > 0 && <span style={{ background: 'var(--bad)', color: '#fff', fontSize: 10.5, fontWeight: 700, fontFamily: 'var(--font-mono)', padding: '0 6px', borderRadius: 8 }}>{n.badge}</span>}
              </button>
            );
          })}
        </nav>

        <div style={{ flex: 1 }} />

        <div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, padding: '10px 12px', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 34, height: 34, borderRadius: 17, background: 'var(--accent-soft)', color: 'var(--accent-deep)', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12 }}>{me.avatar}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: '#fff', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{me.name}</div>
            <div className="mono" style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.5)' }}>{me.badge}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <a href="../index.html" style={{ flex: 1, textAlign: 'center', padding: '8px 10px', background: 'transparent', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, color: 'rgba(255,255,255,0.7)', textDecoration: 'none', fontSize: 12, fontWeight: 500 }}>Tablet</a>
          <button onClick={() => { try { RFP.logout(); } catch(e){} setAuthed(false); }} style={{ flex: 1, padding: '8px 10px', background: 'transparent', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, color: 'rgba(255,255,255,0.7)', fontSize: 12, fontWeight: 500 }}>Sign out</button>
        </div>
      </aside>

      {/* Screen */}
      <main style={{ flex: 1, overflowY: 'auto', padding: '28px 32px 48px', background: 'var(--bg)', position: 'relative' }}>
        {screen === 'home' && <PortalHome go={setScreen} />}
        {screen === 'pay' && <PortalPay />}
        {screen === 'timecards' && <PortalTimecards />}
        {screen === 'pto' && <PortalPTO />}
        {screen === 'reimb' && <PortalReimb />}
        {screen === 'certs' && <PortalCerts />}
        {screen === 'inbox' && <PortalInbox />}
        {screen === 'profile' && <PortalProfile />}
      </main>

      {/* Doc viewer */}
      {activeDoc && (
        <DocViewer open={true} onClose={() => setActiveDoc(null)} title={activeDoc.title} subtitle={activeDoc.subtitle} accent="var(--accent)">
          {activeDoc.el === 'paystub' && <PayStubDoc data={activeDoc.payload} />}
          {activeDoc.el === 'w2' && <W2Doc data={activeDoc.payload} />}
        </DocViewer>
      )}

      {/* Toasts */}
      <div style={{ position: 'absolute', bottom: 20, right: 20, display: 'flex', flexDirection: 'column', gap: 8, zIndex: 700 }}>
        {toasts.map(t => (
          <div key={t.id} className="anim-up" style={{ background: t.kind === 'success' ? 'var(--good)' : t.kind === 'warn' ? 'var(--warn)' : '#0F172A', color: '#fff', padding: '11px 16px', borderRadius: 10, fontSize: 13, fontWeight: 500, boxShadow: 'var(--shadow-lg)', display: 'flex', alignItems: 'center', gap: 8, maxWidth: 340 }}>
            <IconCheckCircle size={16} /> {t.text}
          </div>
        ))}
      </div>
    </>
  );
}

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