/* Lojo for agencies and service providers.

   An agency runs its client's site through the same scan, with its own
   context on top: who they are, what they offer, what the client asked for.
   The full report then also carries a proposal draft in the agency's voice,
   priced from their day rate, built on the findings — the thing Jay called
   the authority layer: Lojo finds the opportunities, the agency pitches and
   bills the work.

   The gate is the same as for a business: the full report and the proposal
   open with an access code the Lojo team hands over. */

const SERVICES = [
  ['web-development', 'Web development'], ['seo-content', 'SEO & content'], ['design', 'Design & brand'],
  ['crm', 'CRM & marketing automation'], ['e-commerce', 'E-commerce'], ['automation', 'AI & workflow automation'],
  ['paid-media', 'Paid media'], ['analytics', 'Analytics & data'], ['other', 'Other'],
];
const BUDGETS = ['Not discussed', 'Under $5k', '$5k–$15k', '$15k–$50k', '$50k+'];
const TIMELINES = ['Not discussed', 'This month', 'This quarter', 'Next 6 months', 'Exploring'];

const field = (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'
});

function Labelled({ label, hint, error, children }) {
  return (
    <label style={{ display: 'block' }}>
      <span style={{ display: 'block', fontSize: 12.5, fontWeight: 500, color: 'var(--fg-muted)', marginBottom: 6 }}>
        {label}{hint && <span style={{ color: 'var(--fg-subtle)', fontWeight: 400 }}> {hint}</span>}
      </span>
      {children}
      <span style={{ display: 'block', minHeight: 15, marginTop: 4, fontSize: 11.5, color: 'var(--crit)', fontFamily: 'var(--font-mono)' }}>{error || ''}</span>
    </label>);
}

function cleanDomain(raw) {
  return (raw || '').trim().replace(/^https?:\/\//i, '').replace(/^www\./i, '').replace(/\/+$/, '').toLowerCase();
}
function validDomain(raw) {
  return /^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d{1,5})?(\/.*)?$/.test(cleanDomain(raw));
}

function AgencyForm({ onDone }) {
  const [v, setV] = React.useState({
    agency: '', name: '', email: '', agency_website: '', services: [],
    company: '', website: '', describe: '', client_contact: '',
    context: '', goals: '', budget: BUDGETS[0], timeline: TIMELINES[0], day_rate: '',
  });
  const [err, setErr] = React.useState({});
  const [phase, setPhase] = React.useState('form');
  const [message, setMessage] = React.useState('');
  const set = (k) => (e) => setV((s) => ({ ...s, [k]: e.target.value }));
  const toggleService = (id) => setV((s) => ({ ...s, services: s.services.includes(id) ? s.services.filter((x) => x !== id) : [...s.services, id] }));

  const validate = () => {
    const e = {};
    if (!v.agency.trim()) e.agency = 'Required';
    if (!v.name.trim()) e.name = 'Required';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.email)) e.email = 'Enter a valid email';
    if (!v.services.length) e.services = 'Pick at least one';
    if (!v.company.trim()) e.company = 'Required';
    if (!validDomain(v.website)) e.website = 'Enter a valid website';
    setErr(e);
    return Object.keys(e).length === 0;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    if (!validate() || phase === 'running') return;
    setPhase('running'); setMessage('');
    try {
      const data = await apiCall('/api/scan', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          kind: 'agency',
          // Sent from the agency workspace: the client is filed under that account.
          agency_token: (() => { try { return sessionStorage.getItem('lojo.agency.token') || ''; } catch (e) { return ''; } })(),
          name: v.name, email: v.email, company: v.company, website: v.website,
          describe: v.describe, role: 'Agency',
          agency: { name: v.agency, website: v.agency_website, services: v.services,
            context: v.context, goals: v.goals, budget: v.budget, timeline: v.timeline,
            day_rate: v.day_rate, client_contact: v.client_contact },
        })
      });
      if (!data.ok && data.errors) {
        const e = { ...data.errors };
        if (e.agency_name) e.agency = e.agency_name;
        if (e.agency_services) e.services = e.agency_services;
        setErr(e); setPhase('form'); return;
      }
      if (!data.ok) { setMessage(data.message || `That did not go through (HTTP ${data.status}).`); setPhase('form'); return; }
      onDone(data, v);
    } catch (e) {
      setMessage('Could not reach the server. Try again in a moment.'); setPhase('form');
    }
  };

  if (phase === 'running') {
    return (
      <div style={{ textAlign: 'center', padding: '60px 0' }}>
        <span style={{ color: 'var(--accent)' }}><Icon name="spinner" size={40} stroke={1.6} /></span>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, marginTop: 16 }}>Reading {cleanDomain(v.website)} the way AI does…</div>
        <div className="mono" style={{ fontSize: 12.5, color: 'var(--fg-subtle)', marginTop: 10 }}>robots.txt · sitemap · pages without JavaScript · structured data · buyer questions</div>
      </div>);
  }

  const two = { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '6px 14px' };
  return (
    <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div>
        <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 12 }}>1 · You</div>
        <div style={two}>
          <Labelled label="Agency or studio" error={err.agency}><input style={field(err.agency)} value={v.agency} onChange={set('agency')} placeholder="Northwind Studio" /></Labelled>
          <Labelled label="Your website" hint="(optional)"><input style={field(false)} value={v.agency_website} onChange={set('agency_website')} placeholder="northwind.studio" /></Labelled>
          <Labelled label="Your name" error={err.name}><input style={field(err.name)} value={v.name} onChange={set('name')} placeholder="Sam Rivera" /></Labelled>
          <Labelled label="Your email" error={err.email}><input style={field(err.email)} value={v.email} onChange={set('email')} placeholder="sam@northwind.studio" /></Labelled>
        </div>
        <Labelled label="What you offer" hint="(the proposal only includes work you do)" error={err.services}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {SERVICES.map(([id, label]) =>
            <button key={id} type="button" onClick={() => toggleService(id)}
              style={{ padding: '8px 13px', borderRadius: 'var(--r-pill)', fontSize: 13, fontFamily: 'var(--font-sans)', cursor: 'pointer',
                border: '1px solid ' + (v.services.includes(id) ? 'var(--accent)' : 'var(--line-strong)'),
                background: v.services.includes(id) ? 'var(--accent)' : 'transparent',
                color: v.services.includes(id) ? 'var(--on-accent)' : 'var(--fg-muted)', fontWeight: v.services.includes(id) ? 600 : 400 }}>
                {label}
              </button>)}
          </div>
        </Labelled>
        <Labelled label="Your day rate" hint="(optional, in dollars — prices the proposal; otherwise $1,200 is assumed)">
          <input style={{ ...field(false), maxWidth: 200 }} value={v.day_rate} onChange={set('day_rate')} placeholder="1200" inputMode="numeric" />
        </Labelled>
      </div>

      <div>
        <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 12 }}>2 · The client</div>
        <div style={two}>
          <Labelled label="Client company" error={err.company}><input style={field(err.company)} value={v.company} onChange={set('company')} placeholder="CircadiaZen" /></Labelled>
          <Labelled label="Client website" error={err.website}><input style={field(err.website)} value={v.website} onChange={set('website')} placeholder="circadiazen.com" /></Labelled>
          <Labelled label="Who you talk to there" hint="(optional)"><input style={field(false)} value={v.client_contact} onChange={set('client_contact')} placeholder="Jordan, head of marketing" /></Labelled>
        </div>
        <Labelled label="What the client does" hint="(in their words if you have them)">
          <textarea style={{ ...field(false), minHeight: 64, resize: 'vertical', lineHeight: 1.5 }} rows={2} value={v.describe} onChange={set('describe')}
            placeholder="Direct-to-consumer sleep supplements, Shopify, mostly US." />
        </Labelled>
      </div>

      <div>
        <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 12 }}>3 · The engagement</div>
        <Labelled label="What they asked you for, and what you have discussed" hint="(this is what makes the proposal theirs)">
          <textarea style={{ ...field(false), minHeight: 96, resize: 'vertical', lineHeight: 1.5 }} rows={4} value={v.context} onChange={set('context')}
            placeholder="They came to us for a site refresh. In the first call they mentioned ChatGPT describes them as a mattress brand, and that their support inbox is mostly the same five questions." />
        </Labelled>
        <Labelled label="Their goals" hint="(optional)">
          <textarea style={{ ...field(false), minHeight: 64, resize: 'vertical', lineHeight: 1.5 }} rows={2} value={v.goals} onChange={set('goals')}
            placeholder="Grow non-paid acquisition; cut support load before the Q4 launch." />
        </Labelled>
        <div style={two}>
          <Labelled label="Budget range">
            <select style={field(false)} value={v.budget} onChange={set('budget')}>{BUDGETS.map((b) => <option key={b}>{b}</option>)}</select>
          </Labelled>
          <Labelled label="Timeline">
            <select style={field(false)} value={v.timeline} onChange={set('timeline')}>{TIMELINES.map((t) => <option key={t}>{t}</option>)}</select>
          </Labelled>
        </div>
      </div>

      <button type="submit" className="btn btn-primary btn-lg" style={{ width: '100%', justifyContent: 'center' }}>
        Scan the client’s site <Icon name="arrow-right" size={19} />
      </button>
      {message && <div style={{ textAlign: 'center', fontSize: 13, color: 'var(--crit)' }}>{message}</div>}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, marginTop: -8, color: 'var(--fg-subtle)' }}>
        <Icon name="lock" size={13} />
        <span className="mono" style={{ fontSize: 11 }}>We only read the client’s public site. Nothing is sent to them.</span>
      </div>
    </form>);
}

function AgencyResult({ scan, form }) {
  const live = scan.mode === 'scanned';
  const slug = scan.slug;
  const [request, setRequest] = React.useState('idle');
  const [message, setMessage] = React.useState('');
  const reportUrl = `/r/?c=${encodeURIComponent(slug)}`;

  React.useEffect(() => {
    if (request !== 'preparing') return undefined;
    const id = setInterval(async () => {
      try {
        const d = await apiCall('/api/report?slug=' + encodeURIComponent(slug));
        if (d.ok && d.report.full_status === 'ready') setRequest('ready');
        else if (d.ok && d.report.full_status === 'failed') setRequest('failed');
      } catch (e) { /* keep waiting */ }
    }, 5000);
    return () => clearInterval(id);
  }, [request, slug]);

  const draft = async () => {
    if (request !== 'idle' && request !== 'error') return;
    setRequest('sending'); setMessage('');
    setTimeout(() => setRequest((r) => (r === 'sending' ? 'preparing' : r)), 1500);
    try {
      const d = await apiCall('/api/request-report', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ slug, name: form.name, email: form.email, website: form.website })
      });
      if (d.ok) setRequest(d.full_status === 'ready' ? 'ready' : d.full_status === 'failed' ? 'failed' : 'preparing');
      else if (d.error === 'payment-required') {
        // No free reports left on the agency's account (or no account yet):
        // the full report is bought, by card, for this client.
        setRequest('paying');
        const err = typeof startCheckout === 'function' ? await startCheckout(slug, 'full_report', form.email) : { message: 'Payments are not loaded on this page.' };
        if (err) { setRequest('error'); setMessage(err.message || 'Could not open the checkout.'); }
      }
      else if (d.error === 'no-report') setRequest('failed');
      else { setRequest('error'); setMessage(d.message || `That did not go through (HTTP ${d.status}).`); }
    } catch (e) {
      setRequest((r) => (r === 'ready' || r === 'failed' ? r : 'preparing'));
    }
  };

  const box = (tone, title, body) =>
  <div style={{ padding: '16px 18px', borderRadius: 'var(--r-md)', background: `var(--${tone}-bg)`,
    border: '1px solid color-mix(in oklab, var(--' + tone + ') 30%, transparent)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: `var(--${tone})`, marginBottom: 6 }}>
        <Icon name={tone === 'accent' ? 'spinner' : 'check'} size={17} stroke={2.4} />
        <span style={{ fontWeight: 600, fontSize: 15 }}>{title}</span>
      </div>
      <div style={{ fontSize: 14, color: 'var(--fg-muted)', lineHeight: 1.6 }}>{body}</div>
    </div>;

  return (
    <div>
      <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: live ? 'var(--good)' : 'var(--warn)', marginBottom: 10 }}>
        {live ? 'Live scan' : 'Captured — the site could not be read'}
      </div>
      <h2 className="display" style={{ fontSize: 'clamp(22px,3.4vw,30px)', margin: '0 0 10px' }}>
        {live ? `What AI sees on ${scan.domain}` : `${scan.domain} could not be scanned`}
      </h2>
      <p style={{ fontSize: 15.5, color: 'var(--fg-muted)', lineHeight: 1.65, margin: '0 0 18px', maxWidth: 680 }}>
        {live
          ? `${scan.counts.critical} critical issue${scan.counts.critical === 1 ? '' : 's'} and ${scan.counts.warning} warning${scan.counts.warning === 1 ? '' : 's'} across ${scan.pages_checked} page${scan.pages_checked === 1 ? '' : 's'}. The free report is on the client page now; the full report adds every finding, the action plan with owners, the 90-day roadmap — and a proposal draft in your voice, priced from your rate.`
          : 'The lead is recorded and the team will look at it by hand. You can still request the proposal; it is written from what the team finds.'}
      </p>
      {live &&
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginBottom: 20 }}>
        {scan.findings.slice(0, 4).map((f, i) => <Finding key={i} f={f} />)}
        {scan.findings.length > 4 && <div className="mono" style={{ textAlign: 'center', fontSize: 12, color: 'var(--fg-subtle)' }}>+ {scan.findings.length - 4} more in the full report</div>}
      </div>}

      {request === 'ready' ? box('good', 'Report and proposal draft are ready',
        <span>They are on the client page, locked with an access code. The Lojo team sends the code to <span style={{ color: 'var(--fg)' }}>{form.email}</span> after a short conversation — that is also where we check the proposal reads right before it goes to your client. <a href={reportUrl} style={{ color: 'var(--accent)' }}>Open the client page</a></span>)
      : request === 'failed' ? box('good', 'Request received',
        <span>The team prepares this one by hand and sends it to <span style={{ color: 'var(--fg)' }}>{form.email}</span> within 24 hours.</span>)
      : request === 'paying' ? box('accent', 'Opening secure checkout…', <span>The full report for this client is paid per website; agencies with an allowance from the Lojo team skip this step.</span>)
      : request === 'preparing' || request === 'sending' ? box('accent', 'Preparing the report and the proposal draft…',
        <span>A few minutes. You can keep this tab open or come back to <a href={reportUrl} style={{ color: 'var(--accent)' }}>the client page</a>.</span>)
      : <button className="btn btn-primary btn-lg" style={{ width: '100%', justifyContent: 'center' }} onClick={draft}>
          Draft the proposal and the full report{scan.pay && scan.pay.enabled && !(scan.pay.owned || {}).full_report && typeof payPrice === 'function' && <span style={{ opacity: 0.85 }}> · {payPrice(scan.pay, 'full_report')}</span>} <Icon name="arrow-right" size={19} />
        </button>}
      {request === 'error' && <div style={{ marginTop: 10, fontSize: 13, color: 'var(--warn)' }}>{message}</div>}
      <WorkspaceStep form={form} />
      <div className="mono" style={{ marginTop: 14, fontSize: 11.5, color: 'var(--fg-subtle)', lineHeight: 1.6 }}>
        Client page: <a href={reportUrl} style={{ color: 'var(--accent)' }}>{window.location.origin}{reportUrl}</a> · free tabs are open now
      </div>
    </div>);
}

/* After the scan: the agency's workspace. Signed in already → this client
   is filed there. Not yet → create the account, prefilled, and the report
   just run is filed under it. */
function WorkspaceStep({ form }) {
  let token = '';
  try { token = sessionStorage.getItem('lojo.agency.token') || ''; } catch (e) { /* private mode */ }
  const q = new URLSearchParams({ signup: '1', name: form.agency || '', website: form.agency_website || '', email: form.email || '' }).toString();
  return (
    <div style={{ marginTop: 16, padding: '16px 18px', borderRadius: 'var(--r-md)', background: 'var(--navy-2)', border: '1px solid color-mix(in oklab, var(--accent) 35%, transparent)' }}>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
        <span className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--accent)' }}>Your agency workspace · beta</span>
      </div>
      {token
        ? <div style={{ fontSize: 14, color: 'var(--fg-muted)', lineHeight: 1.6 }}>This client is filed in your workspace. <a href="admin/" style={{ color: 'var(--accent)' }}>Open the workspace</a> for the report, the access code, the benchmark and the re-scan.</div>
        : <div style={{ fontSize: 14, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
            Create a free account to keep every client you run in one place, hand out access codes, run benchmarks and re-scans, and bring your own engine keys. This report is filed under it automatically.
            <div style={{ marginTop: 10 }}><a href={'admin/?' + q} className="btn btn-primary" style={{ padding: '9px 16px', fontSize: 13.5 }}>Create my workspace</a></div>
          </div>}
    </div>);
}

function AgencyPage() {
  const [result, setResult] = React.useState(null);
  const [form, setForm] = React.useState(null);
  return (
    <React.Fragment>
      <header style={{ borderBottom: '1px solid var(--line)', background: 'var(--navy)' }}>
        <div className="wrap" style={{ padding: 'clamp(26px,4vw,44px) var(--s6)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: 18, flexWrap: 'wrap' }}>
            <a href="../" style={{ textDecoration: 'none' }}><Wordmark size={16} /></a>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <a href="admin/" className="mono" style={{ fontSize: 12, color: 'var(--accent)', textDecoration: 'none' }}>Agency sign in →</a>
              <a href="../" className="mono" style={{ fontSize: 12, color: 'var(--fg-subtle)', textDecoration: 'none' }}>← For businesses</a>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--accent)' }}>For agencies and service providers</div>
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '3px 8px', borderRadius: 999, border: '1px solid var(--line-strong)', color: 'var(--fg-muted)' }}>Beta</span>
          </div>
          <h1 className="display" style={{ fontSize: 'clamp(28px,5vw,44px)', margin: '8px 0 10px', maxWidth: 760 }}>
            Walk into the pitch knowing what AI engines say about your client.
          </h1>
          <p style={{ fontSize: 16.5, color: 'var(--fg-muted)', lineHeight: 1.65, margin: 0, maxWidth: 680 }}>
            Run your client’s site through the AI visibility scan. You get every finding, a prioritised
            action plan with owners, a 90-day roadmap, and a proposal draft in your voice priced from
            your rate — the opportunities, the deliverables, the email. Lojo finds the work; you pitch
            it and bill it.
          </p>
        </div>
      </header>
      <main className="wrap" style={{ padding: 'clamp(28px,5vw,52px) var(--s6) clamp(60px,10vw,120px)', maxWidth: 860 }}>
        {result
          ? <AgencyResult scan={result} form={form} />
          : <AgencyForm onDone={(data, v) => { setResult(data); setForm(v); window.scrollTo({ top: 0, behavior: 'smooth' }); }} />}
      </main>
    </React.Fragment>);
}

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