// "Try it" — interactive section. User types their business + a sample
// customer question. We call window.claude.complete and stream back a
// realistic agent reply. Same specimen-sheet aesthetic as the rest.

function TryItSection() {
  const [biz, setBiz] = React.useState('Lake Norman Dental');
  const [industry, setIndustry] = React.useState('Dental practice in Cornelius, NC');
  const [question, setQuestion] = React.useState('Hi — can I book a cleaning next week? I\'m a new patient.');
  const [reply, setReply] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [count, setCount] = React.useState(0); // session attempt counter

  async function generate() {
    setLoading(true);
    setReply('');
    setErr(null);
    setCount(c => c + 1);
    try {
      const prompt = [
        `You are the AI agent for "${biz}", a ${industry}.`,
        `A customer just sent this message via the website chat:`,
        `"${question}"`,
        ``,
        `Reply as the agent. Be warm, specific, and end with a clear next step.`,
        `Use realistic details (times, prices, addresses) — invented is fine, just stay consistent and concrete.`,
        `Keep it under 60 words. Single paragraph. No headers. No bullet lists.`,
        `Do not introduce yourself with a name or say "I'm an AI"; just answer.`,
      ].join('\n');
      const text = await window.claude.complete(prompt);
      // type it out
      const clean = text.trim().replace(/^["']|["']$/g, '');
      let i = 0;
      const tick = () => {
        i += 2;
        setReply(clean.slice(0, i));
        if (i < clean.length) setTimeout(tick, 14);
        else setLoading(false);
      };
      tick();
    } catch (e) {
      setErr('Could not reach the model. Try again in a moment.');
      setLoading(false);
    }
  }

  const presets = [
    { b: 'Lake Norman Dental', i: 'Dental practice in Cornelius, NC', q: 'Hi — can I book a cleaning next week? I\'m a new patient.' },
    { b: 'Carolina Comfort HVAC', i: 'HVAC contractor in Mooresville, NC, residential service', q: 'My AC stopped overnight. Can someone come today?' },
    { b: 'Brightline Law', i: 'Estate planning firm in Davidson, NC', q: 'Do you handle revocable living trusts? What does it cost?' },
    { b: 'Aurora Pilates', i: 'Boutique pilates studio in Davidson, NC', q: 'Do you have a first-class deal? I\'ve never done pilates.' },
  ];

  const tryStyles = {
    sec: { padding: '120px 0', background: TOKEN.paperDeep, borderTop: `1px solid ${TOKEN.hair}`, borderBottom: `1px solid ${TOKEN.hair}`, position: 'relative' },
    grid: { display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: 0, background: TOKEN.paper, border: `1px solid ${TOKEN.hair}` },
    left: { padding: 32, borderRight: `1px solid ${TOKEN.hair}` },
    right: { padding: 32, background: TOKEN.ink, color: TOKEN.paper, position: 'relative', minHeight: 460 },
    label: { display: 'block', marginBottom: 8 },
    input: {
      width: '100%', background: 'transparent', border: 'none',
      borderBottom: `1px solid ${TOKEN.hair}`,
      padding: '8px 0 12px', marginBottom: 20,
      fontFamily: '"IBM Plex Sans", system-ui', fontSize: 16,
      color: TOKEN.ink, letterSpacing: -0.2, outline: 'none',
    },
    textarea: {
      width: '100%', minHeight: 96, resize: 'none',
      background: 'transparent', border: `1px solid ${TOKEN.hair}`,
      padding: '12px 14px', marginBottom: 14,
      fontFamily: '"IBM Plex Sans", system-ui', fontSize: 15,
      color: TOKEN.ink, letterSpacing: -0.1, outline: 'none',
      lineHeight: 1.45,
    },
    presetRow: {
      display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4, marginBottom: 24,
    },
    preset: {
      padding: '6px 10px', background: 'transparent',
      border: `1px solid ${TOKEN.hair}`, cursor: 'pointer',
      fontFamily: '"IBM Plex Mono", monospace', fontSize: 10,
      letterSpacing: 0.6, textTransform: 'uppercase', color: TOKEN.inkSoft,
    },
  };

  return (
    <section id="try-it" style={tryStyles.sec}>
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '0 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 48, marginBottom: 56 }}>
          <div>
            <SectionLabel num="02" accent={TOKEN.orange}>Try it</SectionLabel>
            <h2 style={{
              fontFamily: '"IBM Plex Sans", system-ui, sans-serif',
              fontWeight: 600, fontSize: 44, letterSpacing: -1.4, lineHeight: 1.08,
              margin: '20px 0 0', color: TOKEN.ink, maxWidth: 420,
            }}>Hear it in <em style={{ fontFamily: '"IBM Plex Serif"', fontStyle: 'italic', fontWeight: 400, color: TOKEN.orange }}>your business's</em> voice.</h2>
          </div>
          <div style={{
            fontSize: 18, lineHeight: 1.55, color: TOKEN.mute,
            letterSpacing: -0.2, maxWidth: 560, paddingTop: 28,
          }}>
            Type your business and a real customer question. We will generate the kind of reply your agent would send. Live model · not a script.
          </div>
        </div>

        <div style={tryStyles.grid}>
          <CornerMark where="tl"/><CornerMark where="tr"/><CornerMark where="bl"/><CornerMark where="br"/>

          {/* prompt column */}
          <div style={tryStyles.left}>
            <Mono color={TOKEN.orange} weight={600}>INPUT · 01</Mono>
            <div style={{ height: 18 }}/>

            <Mono color={TOKEN.mute} style={tryStyles.label}>Business name</Mono>
            <input style={tryStyles.input} value={biz} onChange={e => setBiz(e.target.value)}
              placeholder="Your business name"/>

            <Mono color={TOKEN.mute} style={tryStyles.label}>What you do</Mono>
            <input style={tryStyles.input} value={industry} onChange={e => setIndustry(e.target.value)}
              placeholder="Industry · location"/>

            <Mono color={TOKEN.mute} style={tryStyles.label}>Customer message</Mono>
            <textarea style={tryStyles.textarea} value={question} onChange={e => setQuestion(e.target.value)}
              placeholder="What did the customer say?"/>

            <Mono color={TOKEN.mute} style={tryStyles.label}>Or pick a preset</Mono>
            <div style={tryStyles.presetRow}>
              {presets.map(p => (
                <button key={p.b} style={tryStyles.preset}
                  onClick={() => { setBiz(p.b); setIndustry(p.i); setQuestion(p.q); }}>
                  {p.b.split(' ')[0]}
                </button>
              ))}
            </div>

            <ECButton variant="orange" size="lg" onClick={generate}
              style={{ width: '100%' }}>
              {loading ? 'Generating…' : (count > 0 ? 'Generate again' : 'Generate sample reply')}
            </ECButton>
          </div>

          {/* response column */}
          <div style={tryStyles.right}>
            <Mono color={TOKEN.orange} weight={600}>OUTPUT · 01</Mono>
            <div style={{ marginTop: 18, marginBottom: 28, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{
                width: 40, height: 40, background: TOKEN.orange, color: '#fff',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: '"IBM Plex Mono", monospace', fontWeight: 600, fontSize: 14, letterSpacing: 0.5,
              }}>{(biz || 'XX').split(/\s+/).slice(0,2).map(w => w[0]).join('').toUpperCase().slice(0,2)}</div>
              <div>
                <div style={{ fontFamily: '"IBM Plex Sans"', fontSize: 15, fontWeight: 600, letterSpacing: -0.2 }}>
                  {biz || 'Your business'} · Agent
                </div>
                <div style={{ fontSize: 12, opacity: 0.6, letterSpacing: -0.1 }}>
                  {industry || 'Industry, location'}
                </div>
              </div>
              <div style={{ marginLeft: 'auto' }}>
                <Mono color={TOKEN.paper} style={{ opacity: 0.6 }}>{loading ? 'Thinking…' : 'Idle'}</Mono>
              </div>
            </div>

            {/* customer bubble */}
            {question && (
              <div style={{
                padding: '12px 14px', background: 'rgba(250,250,247,0.06)',
                color: 'rgba(250,250,247,0.7)', fontSize: 13.5, lineHeight: 1.5,
                letterSpacing: -0.1, marginBottom: 12, maxWidth: '85%',
              }}>
                <Mono color="rgba(250,250,247,0.5)" size={9} style={{ marginBottom: 6, display: 'block' }}>CUSTOMER</Mono>
                {question}
              </div>
            )}

            {/* agent reply */}
            <div style={{
              padding: '14px 16px', background: TOKEN.orange, color: '#fff',
              fontSize: 15, lineHeight: 1.55, letterSpacing: -0.1,
              minHeight: 80, marginLeft: '15%',
            }}>
              <Mono color="rgba(255,255,255,0.7)" size={9} style={{ marginBottom: 6, display: 'block' }}>AGENT REPLY</Mono>
              {reply || (loading
                ? <span style={{ opacity: 0.7 }}>▍</span>
                : (err
                  ? <span style={{ opacity: 0.85 }}>{err}</span>
                  : <span style={{ opacity: 0.7 }}>Reply appears here — hit "Generate" on the left.</span>
                )
              )}
              {loading && reply && <span style={{ animation: 'blink 1s steps(2) infinite' }}>▍</span>}
            </div>

            <div style={{
              position: 'absolute', bottom: 20, left: 32, right: 32,
              paddingTop: 14, borderTop: `1px solid rgba(250,250,247,0.12)`,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <Mono color={TOKEN.paper} style={{ opacity: 0.5 }}>SAMPLE ONLY · live model, not your real agent</Mono>
              <Mono color={TOKEN.paper} style={{ opacity: 0.5 }}>RUN · {String(count).padStart(2, '0')}</Mono>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── FAQ accordion ──────────────────────────────────────────────
const FAQS = [
  { q: 'Will you sign an NDA?', a: 'Yes — mutual NDA, our template or yours, before any sensitive details are shared.' },
  { q: 'Do you subcontract?', a: 'Sometimes, with disclosure. Lead engineering is always John.' },
  { q: 'What does the free trial actually include?', a: 'A real, working agent on the channel of your choice, running against your real customers, for two full weeks. No card upfront. No commitment. You walk away with the transcripts either way.' },
  { q: 'What happens after the two weeks?', a: 'If you keep it, you pay a one-time $99 install and choose monthly ($249) or annual ($999). If you don\'t, we turn it off and that\'s the end of it. No card was charged.' },
  { q: 'Are there really no token limits?', a: 'Correct. The monthly and annual prices are flat — talk to as many customers, as often, as you want. The token bill is ours, not yours.' },
  { q: 'What if the engagement runs long?', a: 'The trial is fixed at two weeks. If access to your knowledge base or channels is delayed, the trial pauses and resumes when access is restored. We do not eat into your free time.' },
  { q: 'Refunds?', a: 'Annual subscribers can cancel within the first 30 days for a full refund of the year. The $99 install is non-refundable once the agent is live.' },
  { q: 'What\'s out of scope?', a: 'Voice / phone agents (separate offering), multi-language beyond English + Spanish, and custom CRM integrations beyond HubSpot, Pipedrive, Salesforce, and Sheets (quoted separately).' },
  { q: 'How are payments handled?', a: 'Stripe for monthly and annual subscriptions; ACH or check on request for annual. The $99 install is charged on the day you decide to keep the agent — not before.' },
  { q: 'Do you work on-site?', a: 'Yes within a 30-mile radius of Huntersville, NC, included in the fee. Beyond that, travel is quoted separately. Remote engagements work nationally.' },
];

function FAQItem({ q, a, open, onToggle }) {
  return (
    <div style={{ borderTop: `1px solid ${TOKEN.hair}` }}>
      <button onClick={onToggle} style={{
        width: '100%', padding: '22px 0', background: 'transparent', border: 'none',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        cursor: 'pointer', textAlign: 'left',
      }}>
        <span style={{
          fontFamily: '"IBM Plex Sans"', fontSize: 19, fontWeight: 500,
          letterSpacing: -0.4, color: TOKEN.ink, paddingRight: 24,
        }}>{q}</span>
        <span style={{
          width: 28, height: 28, flexShrink: 0,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          color: TOKEN.orange, border: `1px solid ${TOKEN.hair}`,
          transition: 'transform .2s ease',
          transform: open ? 'rotate(45deg)' : 'rotate(0deg)',
        }}>
          <svg width="12" height="12" viewBox="0 0 12 12">
            <path d="M6 1v10M1 6h10" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
          </svg>
        </span>
      </button>
      <div style={{
        maxHeight: open ? 240 : 0, overflow: 'hidden',
        transition: 'max-height .3s ease',
      }}>
        <div style={{
          padding: '0 60px 24px 0', fontSize: 15.5, lineHeight: 1.6,
          color: TOKEN.mute, letterSpacing: -0.1, maxWidth: 720,
        }}>{a}</div>
      </div>
    </div>
  );
}

function FAQSection() {
  const [open, setOpen] = React.useState(0);
  return (
    <section id="faq" style={{ padding: '120px 0', background: TOKEN.paper, color: TOKEN.ink, position: 'relative' }}>
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '0 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 48, marginBottom: 56 }}>
          <div>
            <SectionLabel num="06" accent={TOKEN.orange}>Questions</SectionLabel>
            <h2 style={{
              fontFamily: '"IBM Plex Sans", system-ui, sans-serif',
              fontWeight: 600, fontSize: 44, letterSpacing: -1.4, lineHeight: 1.08,
              margin: '20px 0 0', color: TOKEN.ink, maxWidth: 420,
            }}>Frequently asked.</h2>
          </div>
          <div style={{
            fontSize: 18, lineHeight: 1.55, color: TOKEN.mute,
            letterSpacing: -0.2, maxWidth: 560, paddingTop: 28,
          }}>
            Things buyers ask before booking the discovery call. If yours is not here, ask on the call — we will answer it in plain English.
          </div>
        </div>
        <div>
          {FAQS.map((f, i) => (
            <FAQItem key={f.q} q={f.q} a={f.a} open={open === i}
              onToggle={() => setOpen(open === i ? -1 : i)}/>
          ))}
          <div style={{ borderTop: `1px solid ${TOKEN.hair}` }}/>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { TryItSection, FAQSection });
