/* Pieces the team admin page and the agency workspace share: inputs,
   buttons, panels, the status pills and the report row. */

const inputStyleAdmin = (bad) => ({
  width: '100%', padding: '12px 13px', borderRadius: 'var(--r-md)', fontSize: 15,
  fontFamily: 'var(--font-sans)', color: 'var(--fg)', background: 'var(--navy)',
  border: '1px solid ' + (bad ? 'var(--crit)' : 'var(--line-strong)'),
  outline: 'none', boxSizing: 'border-box'
});

const smallBtn = (tone) => ({
  background: 'transparent', border: '1px solid ' + (tone ? `var(--${tone})` : 'var(--line-strong)'),
  borderRadius: 'var(--r-pill)', color: tone ? `var(--${tone})` : 'var(--fg-muted)',
  fontFamily: 'var(--font-sans)', fontSize: 13, padding: '7px 14px', cursor: 'pointer'
});

function StatusPills({ r }) {
  const s = r.full_status;
  return (
    <React.Fragment>
      {r.kind === 'agency' && <Pill tone="accent">{r.agency_slug ? `agency · ${r.agency_slug}` : 'agency'}</Pill>}
      {s === 'ready' && <Pill tone="good">full report ready</Pill>}
      {s === 'generating' && <Pill tone="accent">writing full report…</Pill>}
      {s === 'queued' && <Pill tone="accent">queued for the worker</Pill>}
      {r.full_stale && <Pill tone="warn">older than the latest scan</Pill>}
      {s === 'failed' && <Pill tone="crit">generation failed</Pill>}
      {(s === 'not-requested' || s === 'requested') && <Pill tone="warn">free only</Pill>}
      {r.released ? <Pill tone="good">code issued</Pill> : <Pill tone="fg-subtle">no code yet</Pill>}
      {(r.paid || []).includes('full_report') && <Pill tone="good">paid</Pill>}
      {(r.paid || []).some((p) => String(p).startsWith('benchmark')) && <Pill tone="good">benchmark paid</Pill>}
      {r.owned && r.owned.benchmark && !(r.paid || []).some((p) => String(p).startsWith('benchmark')) && <Pill tone="accent">benchmark comped</Pill>}
      {(r.benchmark_state === 'purchased' || r.benchmark_state === 'keys_needed') && <Pill tone="warn">{r.benchmark_state === 'keys_needed' ? 'benchmark: awaiting client keys' : 'benchmark: run it (24h)'}</Pill>}
      {r.requests > 0 && <Pill tone="fg-subtle">asked {r.requests}×</Pill>}
    </React.Fragment>);
}

function Panel({ title, children, tone }) {
  return (
    <div style={{ padding: '18px 20px', borderRadius: 'var(--r-lg)', background: 'var(--navy-2)',
      border: '1px solid ' + (tone ? `color-mix(in oklab, var(--${tone}) 40%, transparent)` : 'var(--line)') }}>
      <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase',
        color: 'var(--fg-subtle)', marginBottom: 12 }}>{title}</div>
      {children}
    </div>);
}

function Row({ label, value }) {
  if (!value) return null;
  return (
    <div style={{ display: 'flex', gap: 12, fontSize: 14, lineHeight: 1.6 }}>
      <span style={{ color: 'var(--fg-subtle)', minWidth: 84, flex: '0 0 auto' }}>{label}</span>
      <span style={{ color: 'var(--fg)', wordBreak: 'break-word' }}>{value}</span>
    </div>);
}

function ReportRow({ r, onOpen }) {
  const c = r.counts || {};
  return (
    <button onClick={() => onOpen(r.slug)} style={{ width: '100%', textAlign: 'left', cursor: 'pointer',
      background: 'var(--navy-2)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)',
      padding: '16px 18px', display: 'flex', flexWrap: 'wrap', gap: 12,
      alignItems: 'center', justifyContent: 'space-between', color: 'var(--fg)', font: 'inherit' }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600 }}>{r.client || r.slug}</div>
        <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginTop: 3 }}>
          {r.domain}{r.agency ? ` · via ${r.agency}` : ''}{r.name ? ` · ${r.name}` : ''}{r.email ? ` · ${r.email}` : ''}
        </div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)', marginTop: 4 }}>
          {r.scan_error ? `scan: ${r.scan_error}` :
            (c.critical !== undefined ? `${c.critical} critical · ${c.warning} warnings` : '')}
          {r.updated_at ? ` · ${String(r.updated_at).slice(0, 16).replace('T', ' ')}` : ''}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 7, alignItems: 'center', flexWrap: 'wrap' }}>
        <StatusPills r={r} />
      </div>
    </button>);
}

function CopyButton({ text, label }) {
  const [done, setDone] = React.useState(false);
  const copy = async () => {
    try { await navigator.clipboard.writeText(text); setDone(true); setTimeout(() => setDone(false), 1500); }
    catch (e) { window.prompt('Copy this:', text); }
  };
  return <button onClick={copy} style={smallBtn()}>{done ? 'Copied' : (label || 'Copy')}</button>;
}


/* "Email the client" — the report link and access code, from the team's
   mailbox. Hidden by the pages until email is configured on the server. */
function EmailClientButton({ onSend, to }) {
  const [state, setState] = React.useState('idle');
  const [msg, setMsg] = React.useState('');
  const go = async () => {
    if (!window.confirm(`Email the report link and access code to ${to}?`)) return;
    setState('sending'); setMsg('');
    try {
      const d = await onSend();
      setState(d.ok ? 'sent' : 'idle');
      setMsg(d.ok ? `Sent to ${d.to}` : (d.message || d.error || 'Could not send.'));
    } catch (e) { setState('idle'); setMsg('Could not reach the server.'); }
  };
  return (
    <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
      <button style={smallBtn('accent')} disabled={state === 'sending'} onClick={go}>{state === 'sending' ? 'Sending…' : state === 'sent' ? 'Sent' : 'Email the client'}</button>
      {msg && <span style={{ fontSize: 12.5, color: state === 'sent' ? 'var(--good)' : 'var(--warn)' }}>{msg}</span>}
    </span>);
}
