/* /partners/ — the preferred partner programme and its application. The
   fee is the first thing on the page and the last thing before the button:
   Lojo is entitled to 5–30% of all implementation fees a partner charges a
   Lojo client, the exact percentage set at approval. The application cannot
   be sent without acknowledging it and accepting the Partner Terms. */

const PARTNER_MODULES = MODULE_CATALOG.filter((m) => m.status !== 'live').map((m) => [m.id, m.title]);

function PartnerForm() {
  const [terms, setTerms] = React.useState(null);
  const [f, setF] = React.useState({ company: '', website: '', name: '', role: '', email: '', regions: '', services: '', modules: [], team_size: '', clients: '', why: '', fee_ack: false });
  const [showTerms, setShowTerms] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const [done, setDone] = React.useState(null);
  const call = (payload) => apiCall('/api/lojo', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
  React.useEffect(() => { call({ module: 'partners', action: 'terms', company: f.company, name: f.name, role: f.role, email: f.email }).then((d) => d.ok && setTerms(d)); }, [f.company, f.name, f.role, f.email]);
  const toggle = (id) => setF({ ...f, modules: f.modules.includes(id) ? f.modules.filter((x) => x !== id) : [...f.modules, id] });
  const send = async () => {
    setBusy(true); setError('');
    const d = await call({ module: 'partners', action: 'apply', ...f });
    setBusy(false);
    if (!d.ok) { setError(d.message || Object.values(d.errors || {}).join(' ') || 'That did not go through.'); return; }
    setDone(d.application);
  };
  const input = (k, props = {}) => <input className="app-input" style={{ width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: '1px solid var(--line-strong)', background: 'var(--navy)', color: 'var(--fg)', font: 'inherit', fontSize: 14 }} value={f[k]} onChange={(e) => setF({ ...f, [k]: e.target.value })} {...props} />;
  const label = (t, el, req) => <label style={{ display: 'block', fontSize: 13, color: 'var(--fg-muted)', marginBottom: 12 }}><span style={{ display: 'block', marginBottom: 6 }}>{t}{req && <span style={{ color: 'var(--accent)' }}> *</span>}</span>{el}</label>;
  if (done) return (
    <div className="card" style={{ padding: 'clamp(22px,3vw,34px)', border: '1px solid var(--accent)' }}>
      <div className="overline" style={{ marginBottom: 8 }}>Application received</div>
      <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600, margin: '0 0 10px' }}>Thank you. We read every application ourselves.</h3>
      <p style={{ margin: 0, color: 'var(--fg-muted)', fontSize: 15, lineHeight: 1.6 }}>Reference <span className="mono">{done.id}</span>. We reply within five business days. If approved, your approval states the platform fee that applies to you, inside the {done.fee_band[0]}–{done.fee_band[1]}% band you accepted, and clients can choose you from inside their workspace.</p>
    </div>);
  return (
    <div id="apply" className="card" style={{ scrollMarginTop: 90, padding: 'clamp(22px,3vw,34px)' }}>
      <div className="overline" style={{ marginBottom: 8 }}>Apply</div>
      <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600, margin: '0 0 16px' }}>Tell us about your firm.</h3>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '0 18px' }}>
        {label('Firm', input('company', { placeholder: 'Northwind Studio' }), true)}
        {label('Website', input('website', { placeholder: 'northwind.example' }))}
        {label('Your name', input('name'), true)}
        {label('Your role', input('role', { placeholder: 'Managing partner' }))}
        {label('Work email', input('email', { type: 'email' }), true)}
        {label('Regions you serve', input('regions', { placeholder: 'North America, UK' }))}
      </div>
      <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginBottom: 6 }}>Modules you can implement <span style={{ color: 'var(--accent)' }}>*</span></div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 14 }}>
        {PARTNER_MODULES.map(([id, t]) => <button key={id} type="button" className={'tour-tab' + (f.modules.includes(id) ? ' on' : '')} style={{ padding: '7px 12px', fontSize: 13 }} onClick={() => toggle(id)}>{t}</button>)}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '0 18px' }}>
        {label('Team size', <select className="app-input" style={{ width: '100%', padding: '10px 12px', borderRadius: 10, border: '1px solid var(--line-strong)', background: 'var(--navy)', color: 'var(--fg)', font: 'inherit', fontSize: 14 }} value={f.team_size} onChange={(e) => setF({ ...f, team_size: e.target.value })}><option value="">Choose</option>{((terms && terms.team_sizes) || ['1–5', '6–20', '21–100', '100+']).map((t) => <option key={t} value={t}>{t}</option>)}</select>)}
        {label('Services, in a line', input('services', { placeholder: 'Process redesign, integrations, change management' }))}
      </div>
      {label('Two or three clients or references we may ask about', <textarea className="app-input" rows={2} style={{ width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: '1px solid var(--line-strong)', background: 'var(--navy)', color: 'var(--fg)', font: 'inherit', fontSize: 14 }} value={f.clients} onChange={(e) => setF({ ...f, clients: e.target.value })} />)}
      {label('Why Lojo clients should work with you', <textarea className="app-input" rows={3} style={{ width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: '1px solid var(--line-strong)', background: 'var(--navy)', color: 'var(--fg)', font: 'inherit', fontSize: 14 }} value={f.why} onChange={(e) => setF({ ...f, why: e.target.value })} />)}

      <div style={{ padding: '16px 18px', borderRadius: 12, border: '1px solid color-mix(in oklab, var(--warn) 55%, transparent)', background: 'color-mix(in oklab, var(--warn) 7%, var(--navy))', margin: '6px 0 14px' }}>
        <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 6 }}>The platform fee, in plain words</div>
        <p style={{ margin: '0 0 10px', fontSize: 14, lineHeight: 1.6 }}>By applying you accept that <b>Lojo (Eureka Advisory LLC) is entitled to a percentage of all implementation fees you charge a Lojo client, between {terms ? terms.fee_band[0] : 5}% and {terms ? terms.fee_band[1] : 30}%</b>. The exact percentage is set in your approval and may be set per engagement within that band:</p>
        <ul style={{ margin: '0 0 10px', paddingLeft: 18, fontSize: 13.5, lineHeight: 1.6, color: 'var(--fg-muted)' }}>
          {(terms ? terms.fee_bands : [{ pct: 30, when: 'Lojo sourced the client and scoped the work from its own analysis' }, { pct: 15, when: 'the partner brought the client to Lojo and Lojo scoped the work' }, { pct: 5, when: "the partner's own client, with Lojo used for delivery only" }]).map((b) => <li key={b.pct}><b style={{ color: 'var(--fg)' }}>{b.pct}%</b> where {b.when}</li>)}
        </ul>
        <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.6, color: 'var(--fg-muted)' }}>You report Lojo-client invoices monthly and pay within thirty days of being paid. Everyone from your firm who enters a client workspace signs the Implementation Partner Confidentiality Agreement: no copying, re-branding or passing off Lojo's software, methods or recommendations.</p>
        <button type="button" className="app-btn small" style={{ marginTop: 10, padding: '6px 10px', fontSize: 12.5, borderRadius: 8, border: '1px solid var(--line-strong)', background: 'transparent', color: 'var(--fg)', cursor: 'pointer' }} onClick={() => setShowTerms(!showTerms)}>{showTerms ? 'Hide the full Partner Terms' : 'Read the full Partner Terms'}</button>
        {showTerms && <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'var(--font-sans)', fontSize: 13, lineHeight: 1.6, color: 'var(--fg-muted)', background: 'var(--navy)', border: '1px solid var(--line)', borderRadius: 10, padding: 16, marginTop: 10, maxHeight: 420, overflowY: 'auto' }}>{terms ? terms.text : 'Loading…'}</pre>}
      </div>
      <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 14, lineHeight: 1.6, marginBottom: 14 }}>
        <input type="checkbox" checked={f.fee_ack} onChange={(e) => setF({ ...f, fee_ack: e.target.checked })} style={{ marginTop: 4 }} />
        <span>I am authorised to apply for {f.company || 'my firm'}. I understand that Lojo is entitled to between {terms ? terms.fee_band[0] : 5}% and {terms ? terms.fee_band[1] : 30}% of all implementation fees we charge a Lojo client, the exact percentage set in our approval, and I accept the Preferred Partner Terms (version {terms ? terms.version : '…'}) on my firm's behalf.</span>
      </label>
      {error && <div style={{ color: 'var(--warn)', fontSize: 13.5, marginBottom: 10 }}>{error}</div>}
      <button className="btn btn-primary btn-lg" disabled={busy || !f.fee_ack || !f.company || !f.name || !/@/.test(f.email) || !f.modules.length} onClick={send}>{busy ? 'Sending…' : 'Apply to the programme'} <Icon name="arrow-right" size={18} /></button>
      <div style={{ fontSize: 12, color: 'var(--fg-subtle)', marginTop: 10 }}>Read only by the Lojo founders. We reply within five business days.</div>
    </div>);
}

function PartnersPage() {
  React.useEffect(() => { countOpen('partners_page'); }, []);
  const gets = [
    ['Clients with a plan already made', 'Every Lojo client arrives with a graded analysis, prioritised recommendations and a roadmap. You scope against evidence, not a discovery phase.'],
    ['Chosen from inside the workspace', 'Clients pick a preferred partner by module and region without leaving Lojo. You are brought into their workspace, with the same ledger and roadmap they see.'],
    ['A seat that costs them nothing', 'Approved implementers never use a client seat, so there is no friction in bringing you in.'],
    ['Your work, your fees', 'You contract with the client directly and set your own prices. Lojo takes its share from you, never a markup on the client.'],
  ];
  const expects = [
    ['The platform fee', 'Between 5% and 30% of all implementation fees you charge a Lojo client, set at approval and per engagement within the band. Reported monthly, paid within thirty days of being paid.'],
    ['Strict confidentiality', 'Everyone from your firm who enters a client workspace signs the Implementation Partner Confidentiality Agreement. No copying, re-branding or passing off Lojo\'s software, methods, analyses or recommendations. No building a competing tool from what you see.'],
    ['No circumvention', 'No routing a Lojo client\'s work around Lojo to avoid the fee, during the programme and for twenty-four months after.'],
    ['Approval, every time', 'Lojo approves you once for the programme and again for each client engagement; access can be revoked at any time.'],
  ];
  return (
    <React.Fragment>
      <PageNav active="/partners/" cta={{ href: '#apply', label: 'Apply' }} />
      <header className="section" style={{ paddingTop: 136, paddingBottom: 'clamp(24px,4vw,40px)', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -120, left: '50%', transform: 'translateX(-50%)', width: 900, height: 520, background: 'radial-gradient(closest-side, var(--accent-glow), transparent)', opacity: 0.45, pointerEvents: 'none', filter: 'blur(20px)', maxWidth: '150vw' }}></div>
        <div className="wrap" style={{ position: 'relative', textAlign: 'center' }}>
          <div className="overline" style={{ marginBottom: 16 }}>Preferred partners</div>
          <h1 className="display" style={{ fontSize: 'clamp(34px,6.4vw,66px)', margin: '0 auto', maxWidth: 940 }}>Lojo plans the work.<br />Preferred partners <span style={{ color: 'var(--accent)' }}>do it</span>.</h1>
          <p className="lede" style={{ maxWidth: 680, margin: '20px auto 0', color: 'var(--fg-muted)' }}>
            Lojo analyses an organization, writes the strategy and runs the execution in its workspace. It does not do the implementation. Implementation firms that join the programme are chosen by clients from inside the workspace, and pay Lojo a share of what they charge: <b style={{ color: 'var(--fg)' }}>between 5% and 30% of all implementation fees</b>, set at approval.
          </p>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'center', marginTop: 26, flexWrap: 'wrap' }}><a href="#apply" className="btn btn-primary">Apply to the programme <Icon name="arrow-right" size={16} /></a><a href="/modules/" className="btn btn-ghost">See the modules</a></div>
        </div>
      </header>

      <section className="section" style={{ paddingTop: 0 }}>
        <div className="wrap">
          <SectionHead over="What you get" center title="Clients who already know<br>what needs doing." />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 'clamp(14px,2vw,22px)' }}>
            {gets.map(([t, d]) => <div key={t} className="card feature-card" style={{ padding: 'clamp(18px,2.4vw,26px)' }}><div style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 600, marginBottom: 6 }}>{t}</div><p style={{ margin: 0, fontSize: 14.5, color: 'var(--fg-muted)', lineHeight: 1.6 }}>{d}</p></div>)}
          </div>
        </div>
      </section>

      <section className="section" style={{ background: 'var(--navy)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
        <div className="wrap">
          <SectionHead over="What Lojo expects" center title="The terms, before you read them<br>in full." />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 'clamp(14px,2vw,22px)' }}>
            {expects.map(([t, d], i) => <div key={t} className="card" style={{ padding: 'clamp(18px,2.4vw,26px)', borderColor: i === 0 ? 'var(--warn)' : 'var(--line-strong)' }}><div style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 600, marginBottom: 6, color: i === 0 ? 'var(--warn)' : 'var(--fg)' }}>{t}</div><p style={{ margin: 0, fontSize: 14.5, color: 'var(--fg-muted)', lineHeight: 1.6 }}>{d}</p></div>)}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="wrap" style={{ maxWidth: 900 }}>
          <PartnerForm />
        </div>
      </section>
      <Footer />
    </React.Fragment>);
}

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