// Login + mode picker components
const { useState, useEffect, useRef, useMemo, useCallback } = React;

function Topbar({ user, onLogout, crumb, saveLabel }) {
  const initials = (user?.name || "U").split(" ").map(s=>s[0]).join("").slice(0,2).toUpperCase();
  const sub = user ? (user.isAdmin ? "Engagement lead · Admin" : "Respondent") : "";
  return (
    <div className="topbar">
      <img src="assets/logo.png" alt="Wellbeing Outfit" className="logo" />
      {crumb && <div className="crumb">{crumb}</div>}
      <div className="spacer"></div>
      {saveLabel !== false && <div className="save-badge">{saveLabel || "Auto-saved"}</div>}
      {user && (
        <div className="user">
          <div className="avatar">{initials}</div>
          <div>
            <div style={{fontWeight:600}}>{user.name}</div>
            <div style={{fontSize:11,color:"var(--muted)"}}>{sub}</div>
          </div>
          <button className="btn ghost" style={{marginLeft:10,padding:"6px 10px",fontSize:12}} onClick={onLogout}>Sign out</button>
        </div>
      )}
    </div>
  );
}

function Login({ onLogin }) {
  const [name, setName] = useState("");
  const [pw, setPw] = useState("");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

  async function submit(e) {
    e.preventDefault();
    setErr("");
    if (!name.trim() || name.trim().length < 2) { setErr("Please enter your name."); return; }
    if (pw.length < 4) { setErr("Please enter your access code."); return; }
    setBusy(true);
    try {
      const data = await window.api.post("/api/auth/login", { name: name.trim(), password: pw });
      onLogin(data.user);
    } catch (ex) {
      setErr(ex.message || "Sign-in failed");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="login-shell">
      <div className="left">
        <div className="logo-white">
          <span className="a">wellbeing</span>
          <span className="dot"></span>
          <span className="b">outfit</span>
        </div>
        <div className="pitch">
          <h1>Let's get the picture <em>before</em> we sit down.</h1>
          <p>This short survey gives us a clear view of how your team currently handles data and uses AI — so the strategy work we do together is grounded in your reality, not assumptions.</p>
        </div>
        <div className="meta">Discovery · Week 1 · Confidential</div>
      </div>
      <div className="right">
        <div className="login-card">
          <h2>Sign in to begin</h2>
          <p className="sub">Enter your name and the access code shared with you. Your responses save automatically.</p>
          <form onSubmit={submit}>
            <label>Your name</label>
            <input type="text" placeholder="e.g. Sam Whitlock" value={name} onChange={e=>setName(e.target.value)} autoFocus autoComplete="name" />
            <label>Access code</label>
            <input type="password" placeholder="Shared with you by your engagement lead" value={pw} onChange={e=>setPw(e.target.value)} autoComplete="current-password" />
            <div className="row">
              <label style={{display:"flex",gap:6,alignItems:"center",margin:0,fontSize:13,textTransform:"none",letterSpacing:0,fontWeight:400,color:"var(--muted)"}}>
                <input type="checkbox" defaultChecked /> Remember this device
              </label>
              <span style={{fontSize:12,color:"var(--muted)"}}>Confidential</span>
            </div>
            {err && <div className="err">{err}</div>}
            <button type="submit" className="submit" disabled={busy}>{busy ? "Signing in…" : "Continue"}</button>
            <div className="helper-pill">
              <div>
                <strong>Confidential.</strong> Responses are visible only to your engagement lead. You can revise answers at any time before submission.
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}

function ModePicker({ user, onPick, onOpenDeck, onLogout }) {
  return (
    <>
      <Topbar user={user} onLogout={onLogout} crumb="Choose how you'd like to begin" saveLabel={false} />
      <div className="mode-shell">
        <h1 className="hello">Hello, <em>{user.name.split(" ")[0]}</em>.</h1>
        <p className="lead">
          We've put together a discovery survey to help us understand how Wellbeing Outfit currently handles data and AI tools. It takes about 15&ndash;25 minutes. Pick the format that suits you best — you can switch at any time and your answers will carry across.
        </p>
        <div className="mode-grid">
          <div className="mode-card" onClick={() => onPick("standard")}>
            <div className="preview standard">
              <div className="progress-mini"></div>
              <div style={{marginTop:6}} className="q">Q1 of 28 — Which AI tools does your team use?</div>
              <div style={{display:"flex",flexWrap:"wrap",gap:6,marginTop:4}}>
                <div className="opt sel">ChatGPT (personal)</div>
                <div className="opt">Claude</div>
                <div className="opt sel">Microsoft Copilot</div>
                <div className="opt">Gemini</div>
              </div>
            </div>
            <h3>Standard survey</h3>
            <p>Walk through the questions one section at a time. Pick options, add notes where helpful, and submit when ready.</p>
            <div className="meta">
              <span>~15 min</span>
              <span>9 sections</span>
              <span>Auto-saved</span>
            </div>
            <button className="cta">Start the survey →</button>
          </div>

          <div className="mode-card recommended" onClick={() => onPick("chat")}>
            <div className="preview chat">
              <div className="bubble bot">Which AI tools does the team reach for most?</div>
              <div className="bubble user">Mostly ChatGPT — and Granola for meeting notes.</div>
              <div className="pill">Q1 auto-filled · 92%</div>
              <div className="bubble bot">Got it. And does anyone have rules about what's okay to put in?</div>
            </div>
            <h3>Chat with our AI assistant</h3>
            <p>Have a conversation about how you work. The assistant listens, fills in answers as it picks up signal, and shows exactly what it inferred and how confident it is. You review everything before submitting.</p>
            <div className="meta">
              <span>~10 min</span>
              <span>Conversational</span>
              <span>Review &amp; adjust</span>
            </div>
            <button className="cta">Start a conversation →</button>
          </div>
        </div>

        {onOpenDeck && (
          <div className="deck-promo" onClick={onOpenDeck} role="button" tabIndex={0} onKeyDown={(e)=>{ if(e.key==="Enter"||e.key===" "){e.preventDefault();onOpenDeck();} }}>
            <div className="deck-promo-l">
              <div className="deck-promo-eye">For your reference</div>
              <h3>AI Transformation Roadmap</h3>
              <p>Our recommended programme — what we'd build, how it's sequenced, and why. Open as an interactive presentation.</p>
            </div>
            <div className="deck-promo-r">
              <div className="deck-promo-meta">25 slides · ~12 min</div>
              <div className="deck-promo-cta">Open deck →</div>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { Topbar, Login, ModePicker });
