/* The agency workspace: /agency/admin/.

   An agency signs in with the login the Lojo team gave it, sees the clients
   it brought (with each access code), opens a client to read the full
   report, run the benchmark or a re-scan, and keeps its own API keys for
   the engines Lojo does not pay for. The session token is signed by the
   server; the engines and verify routes accept it only for this agency's
   own clients. */

const AGENCY_TOKEN_KEY = 'lojo.agency.token';

function readAgencyToken() { try { return sessionStorage.getItem(AGENCY_TOKEN_KEY) || ''; } catch (e) { return ''; } }
function writeAgencyToken(t) { try { t ? sessionStorage.setItem(AGENCY_TOKEN_KEY, t) : sessionStorage.removeItem(AGENCY_TOKEN_KEY); } catch (e) { /* private mode */ } }

async function agencyCall(token, body) {
  return apiCall('/api/agency', { method: 'POST', headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: 'Bearer ' + token } : {}) },
    body: JSON.stringify(body) });
}

function AgencyLogin({ onIn }) {
  const params = new URLSearchParams(window.location.search);
  const [mode, setMode] = React.useState(params.get('signup') ? 'signup' : 'login');
  const [login, setLogin] = React.useState(params.get('email') || '');
  const [password, setPassword] = React.useState('');
  const [name, setName] = React.useState(params.get('name') || '');
  const [website, setWebsite] = React.useState(params.get('website') || '');
  const [email, setEmail] = React.useState(params.get('email') || '');
  const [state, setState] = React.useState('idle');
  const [message, setMessage] = React.useState('');
  const submit = async (e) => {
    e.preventDefault();
    if (state === 'sending') return;
    setState('sending'); setMessage('');
    try {
      const d = mode === 'signup'
        ? await agencyCall('', { action: 'signup', name, website, email, password, origin: window.location.origin })
        : await agencyCall('', { action: 'login', login, password });
      if (d.ok) { writeAgencyToken(d.token); onIn(d.token); return; }
      setState('idle'); setMessage(d.message || `That did not work (HTTP ${d.status}).`);
    } catch (err) { setState('idle'); setMessage('Could not reach the server.'); }
  };
  const tab = (m, label) => <button type="button" onClick={() => { setMode(m); setMessage(''); }} style={{ ...smallBtn(mode === m ? 'accent' : undefined), padding: '8px 16px' }}>{label}</button>;
  return (
    <div style={{ maxWidth: 440, margin: '0 auto', padding: 'clamp(50px,10vh,120px) 0' }}>
      <div style={{ textAlign: 'center', marginBottom: 24 }}>
        <Wordmark size={16} />
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--fg-subtle)', marginTop: 14 }}>Agency workspace · beta</div>
      </div>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 18 }}>{tab('login', 'Sign in')}{tab('signup', 'Create an account')}</div>
      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {mode === 'signup'
          ? <React.Fragment>
              <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Agency or studio name" style={inputStyleAdmin(false)} />
              <input value={website} onChange={(e) => setWebsite(e.target.value)} placeholder="Agency website (optional)" style={inputStyleAdmin(false)} />
              <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Work email" autoComplete="email" style={inputStyleAdmin(false)} />
              <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Choose a password (8+ characters)" autoComplete="new-password" style={inputStyleAdmin(!!message)} />
            </React.Fragment>
          : <React.Fragment>
              <input value={login} onChange={(e) => setLogin(e.target.value)} placeholder="Agency login (name or email)" autoComplete="username" style={inputStyleAdmin(false)} />
              <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" autoComplete="current-password" style={inputStyleAdmin(!!message)} />
            </React.Fragment>}
        <button type="submit" className="btn btn-primary btn-lg" disabled={state === 'sending'} style={{ width: '100%', justifyContent: 'center' }}>
          {state === 'sending' ? (mode === 'signup' ? 'Creating…' : 'Signing in…') : (mode === 'signup' ? 'Create my workspace' : 'Sign in')}
        </button>
      </form>
      {message && <div style={{ marginTop: 12, textAlign: 'center', fontSize: 13, color: 'var(--crit)' }}>{message}</div>}
      <div style={{ marginTop: 22, textAlign: 'center', fontSize: 13, color: 'var(--fg-subtle)', lineHeight: 1.6 }}>
        {mode === 'signup'
          ? 'Any client analysis you already ran under this agency name, website or email is filed into your workspace automatically.'
          : <span>New here? Create an account above, or <a href="/agency/" style={{ color: 'var(--accent)' }}>run a client analysis</a> first.</span>}
      </div>
    </div>);
}

function AgencyClient({ slug, token, me, onBack, onExpired }) {
  const [report, setReport] = React.useState(null);
  const [error, setError] = React.useState('');
  const [tab, setTab] = React.useState(0);
  const load = React.useCallback(() => {
    agencyCall(token, { action: 'client', slug }).then((d) => {
      if (d.status === 401) { onExpired(); return; }
      if (d.ok) setReport(d.report); else setError((d.message || 'Could not load that client.') + (d.detail ? '\n\n' + String(d.detail).slice(-1500) : ''));
    }).catch(() => setError('Could not reach the server.'));
  }, [slug, token]);
  React.useEffect(() => { load(); }, [load]);
  const status = report && report.full_status;
  React.useEffect(() => {
    if (status !== 'generating' && status !== 'queued' && status !== 'requested') return undefined;
    const id = setInterval(load, 6000);
    return () => clearInterval(id);
  }, [status, load]);
  if (error) return <div style={{ color: 'var(--fg-muted)' }}>{error}</div>;
  if (!report) return <div style={{ color: 'var(--fg-subtle)' }}>Loading…</div>;
  const lead = report.lead || {};
  const sections = [
    ...((report.free && report.free.sections) || []).map((s) => ({ tab: s.tab, tier: 'free', render: () => <Section s={s} /> })),
    ...fullTabs(report, { token }).map((t) => ({ ...t, tier: 'full' })),
  ];
  const current = sections[Math.min(tab, sections.length - 1)];
  const clientLink = `${window.location.origin}/r/?c=${slug}`;
  const code = report.access_code;
  const features = (me && me.features) || {};
  return (
    <div>
      <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: 'var(--fg-subtle)', fontFamily: 'var(--font-mono)', fontSize: 12, cursor: 'pointer', padding: 0, marginBottom: 18 }}>← Your clients</button>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap', marginBottom: 4 }}>
        <h1 className="display" style={{ fontSize: 'clamp(24px,5vw,36px)', margin: 0 }}>{report.client || slug}</h1>
        <StatusPills r={{ ...report, requests: (report.requests || []).length, kind: report.kind }} />
      </div>
      <div style={{ fontSize: 14, color: 'var(--fg-muted)', marginBottom: 22, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
        <span>{report.domain}</span><span>·</span>
        <a href={clientLink} target="_blank" rel="noreferrer" className="mono" style={{ color: 'var(--accent)' }}>{clientLink}</a>
        <CopyButton text={clientLink} label="Copy link" />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 14, marginBottom: 26 }}>
        <Panel title="The client">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <Row label="Contact" value={lead.name} />
            <Row label="Email" value={lead.email} />
            <Row label="Website" value={lead.website} />
            <Row label="Received" value={String(lead.received_at || '').slice(0, 16).replace('T', ' ')} />
            {lead.describe && <Row label="They do" value={lead.describe} />}
          </div>
        </Panel>
        <Panel title="Access code" tone={code ? 'good' : undefined}>
          {code
            ? <React.Fragment>
                <div className="mono" style={{ fontSize: 24, letterSpacing: '0.08em', marginBottom: 10 }}>{code}</div>
                <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6, marginBottom: 12 }}>Opens the full report at the link above. Give it to your client when you are ready; it also opens pitch mode for you on that page.</div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <CopyButton text={code} label="Copy code" />
                  <CopyButton text={`Your full AI visibility report for ${report.domain} is ready at ${clientLink}\nAccess code: ${code}`} label="Copy message for client" />
                  {me && me.mail_configured && typeof EmailClientButton === 'function' &&
                  <EmailClientButton onSend={() => agencyCall(token, { action: 'email-client', slug, origin: window.location.origin })} to={lead.email} />}
                </div>
              </React.Fragment>
            : <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
                {status === 'ready' ? 'The Lojo team has not issued a code yet.' : status === 'queued' || status === 'generating' || status === 'requested'
                  ? 'The full report is being written; the code appears here when it is ready.' : 'The full report has not been requested yet. Unlock it from the client link.'}
              </div>}
        </Panel>
      </div>
      {features.benchmark && typeof BenchmarkPanel === 'function' &&
      <div style={{ marginBottom: 26 }}><BenchmarkPanel slug={slug} token={token} report={report} onExpired={onExpired} onReportChanged={load} /></div>}
      {features.verify && typeof VerifyPanel === 'function' &&
      <div style={{ marginBottom: 26 }}><VerifyPanel slug={slug} token={token} report={report} onExpired={onExpired} onReportChanged={load} /></div>}
      {sections.length === 0
        ? <div style={{ color: 'var(--fg-muted)' }}>No report sections yet.</div>
        : <React.Fragment>
            <div style={{ display: 'flex', gap: 4, overflowX: 'auto', borderBottom: '1px solid var(--line)', marginBottom: 24 }}>
              {sections.map((s, i) =>
              <button key={i} onClick={() => setTab(i)} style={{ flex: '0 0 auto', padding: '12px 12px', background: 'transparent', border: 'none',
                borderBottom: '2px solid ' + (i === tab ? 'var(--accent)' : 'transparent'), color: i === tab ? 'var(--fg)' : 'var(--fg-muted)',
                fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: i === tab ? 600 : 400, cursor: 'pointer', whiteSpace: 'nowrap' }}>{s.tab}</button>)}
            </div>
            {current.render()}
          </React.Fragment>}
    </div>);
}

function AgencySettings({ token, me, onChanged, onExpired }) {
  const [busy, setBusy] = React.useState('');
  const [flash, setFlash] = React.useState('');
  const [reps, setReps] = React.useState((me.agency.settings || {}).reps || 3);
  const [pw, setPw] = React.useState({ current: '', next: '' });
  const act = async (body, after) => {
    setBusy(body.action); setFlash('');
    try {
      const d = await agencyCall(token, body);
      if (d.status === 401) { onExpired(); return; }
      if (!d.ok) setFlash(d.message || d.error || 'That did not work.');
      else { if (after) after(d); onChanged(); }
    } catch (e) { setFlash('Could not reach the server.'); }
    setBusy('');
  };
  const engines = me.engines || [];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {flash && <div style={{ fontSize: 13.5, color: 'var(--warn)' }}>{flash}</div>}
      <Panel title="Engines and your API keys">
        <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.6, marginBottom: 12 }}>
          Claude runs on Lojo's key for every client, at no cost to you. The other engines run on your own keys, billed to your accounts,
          for every client you bring. Keys are stored encrypted; only the last four characters ever come back to this page.
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 14 }}>
          {engines.map((e) => <Pill key={e.id} tone={e.lojo || e.own_key ? 'good' : 'fg-subtle'}>{ENGINE_SHORT[e.id]} · {e.lojo ? 'included' : e.own_key ? 'your key' : 'needs your key'}</Pill>)}
        </div>
        {!me.key_store && <div style={{ fontSize: 13, color: 'var(--crit)', marginBottom: 10 }}>Keys cannot be stored on this deployment yet; ask the Lojo team.</div>}
        <EngineKeysForm tails={me.keys || {}} busy={busy === 'keys'} onSave={(keys) => act({ action: 'keys', keys })} />
      </Panel>
      <Panel title="Defaults">
        <label style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 13.5, color: 'var(--fg-muted)' }}>
          Runs per prompt in a benchmark
          <input type="number" min={1} max={10} value={reps} onChange={(e) => setReps(Math.max(1, Math.min(10, Number(e.target.value) || 1)))} style={{ ...inputStyleAdmin(false), width: 70, padding: '7px 9px', fontSize: 13 }} />
          <button style={smallBtn()} disabled={!!busy} onClick={() => act({ action: 'settings', reps })}>Save</button>
        </label>
      </Panel>
      <Panel title="Full reports and billing">
        <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
          {me && me.payments && me.payments.enabled
            ? <span>
                {me.allowance && me.allowance.free_reports > 0
                  ? <span><span style={{ color: 'var(--fg)', fontWeight: 600 }}>{me.allowance.remaining} of {me.allowance.free_reports}</span> free full reports left on this account. </span>
                  : 'This account has no free-report allowance. '}
                Beyond that, each client’s full report is {payPrice(me.payments, 'full_report')} and the engine benchmark add-on {payPrice(me.payments, 'benchmark_byok')} on your own engine keys or {payPrice(me.payments, 'benchmark_managed')} on Lojo’s, paid by card from the client’s report page or when you request it here.
                Ask the Lojo team about an allowance for your volume. <a href="/pricing/" style={{ color: 'var(--accent)' }}>Pricing</a>
              </span>
            : 'Full reports and benchmarks are open on this deployment: nothing is charged.'}
        </div>
      </Panel>
      <Panel title="Account">
        <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', marginBottom: 10 }}>{me.agency.name} · login <span className="mono">{me.agency.slug}</span>{me.agency.email ? ` or ${me.agency.email}` : ''}</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <input type="password" value={pw.current} onChange={(e) => setPw({ ...pw, current: e.target.value })} placeholder="Current password" autoComplete="current-password" style={{ ...inputStyleAdmin(false), width: 200, padding: '8px 10px', fontSize: 13 }} />
          <input type="password" value={pw.next} onChange={(e) => setPw({ ...pw, next: e.target.value })} placeholder="New password (8+ characters)" autoComplete="new-password" style={{ ...inputStyleAdmin(false), width: 220, padding: '8px 10px', fontSize: 13 }} />
          <button style={smallBtn('accent')} disabled={!!busy || !pw.current || pw.next.length < 8} onClick={() => act({ action: 'password', current: pw.current, new: pw.next }, () => { setPw({ current: '', next: '' }); setFlash('Password changed.'); })}>Change password</button>
        </div>
      </Panel>
    </div>);
}

function AgencyPage() {
  const [token, setToken] = React.useState(readAgencyToken());
  const [me, setMe] = React.useState(null);
  const [clients, setClients] = React.useState(null);
  const [error, setError] = React.useState('');
  const [view, setView] = React.useState('clients');
  const [open, setOpen] = React.useState('');
  const signOut = React.useCallback(() => { writeAgencyToken(''); setToken(''); setMe(null); setClients(null); setOpen(''); }, []);
  const load = React.useCallback(() => {
    if (!token) return;
    Promise.all([agencyCall(token, { action: 'me' }), agencyCall(token, { action: 'clients' })]).then(([m, c]) => {
      if (m.status === 401 || c.status === 401) { signOut(); return; }
      if (m.ok) setMe(m); if (c.ok) setClients(c.clients); setError(m.ok && c.ok ? '' : (m.message || c.message || 'Could not load.'));
    }).catch(() => setError('Could not reach the server.'));
  }, [token, signOut]);
  React.useEffect(() => { load(); }, [load, open, view]);
  if (!token) return <AgencyLogin onIn={setToken} />;
  const navBtn = (v, label) => <button onClick={() => { setView(v); setOpen(''); }} style={{ ...smallBtn(view === v && !open ? 'accent' : undefined) }}>{label}</button>;
  return (
    <div className="wrap" style={{ padding: 'clamp(28px,5vw,56px) var(--s6) 120px', maxWidth: 980 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, marginBottom: 'clamp(24px,4vw,40px)', flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Wordmark size={15} />
          {me && <span className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--fg-subtle)' }}>{me.agency.name}</span>}
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {navBtn('clients', 'Clients')}
          {navBtn('settings', 'Settings & keys')}
          <a href="/agency/" className="btn btn-primary" style={{ padding: '7px 14px', fontSize: 13 }}>+ New client analysis</a>
          <button onClick={signOut} style={smallBtn()}>Sign out</button>
        </div>
      </div>
      {error && <div style={{ color: 'var(--crit)', marginBottom: 16 }}>{error}</div>}
      {open
        ? <AgencyClient slug={open} token={token} me={me} onBack={() => setOpen('')} onExpired={signOut} />
        : view === 'settings' && me
          ? <AgencySettings token={token} me={me} onChanged={load} onExpired={signOut} />
          : <React.Fragment>
              <h1 className="display" style={{ fontSize: 'clamp(24px,5vw,36px)', margin: '0 0 8px' }}>Your clients</h1>
              <p style={{ fontSize: 15, color: 'var(--fg-muted)', margin: '0 0 18px', maxWidth: 680, lineHeight: 1.6 }}>
                Every client you ran a free report for while signed in. Open one for the report, its access code, the benchmark and the re-scan.
              </p>
              {clients === null && !error && <div style={{ color: 'var(--fg-subtle)' }}>Loading…</div>}
              {clients && clients.length === 0 &&
              <div style={{ padding: '28px 24px', borderRadius: 'var(--r-lg)', background: 'var(--navy-2)', border: '1px solid var(--line)', color: 'var(--fg-muted)', fontSize: 14.5, lineHeight: 1.7 }}>
                  <div style={{ color: 'var(--fg)', fontWeight: 600, marginBottom: 8 }}>No clients yet.</div>
                  Use "New client analysis" above while signed in and the client is filed here. Clients you ran before signing in can be moved here by the Lojo team.
                </div>}
              {clients && clients.length > 0 &&
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>{clients.map((r) => <ReportRow key={r.slug} r={r} onOpen={setOpen} />)}</div>}
            </React.Fragment>}
    </div>);
}

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