/* ====================== OKTRA — FAQ, contact, footer ====================== */

const FAQS = [
  { q: 'Who do you actually work with?', a: 'Founders and small teams who want to move fast, ops leaders inside larger organizations, other agencies and dev shops that need a force-multiplier, and industry operators in real estate, education, and services who know AI should be doing more for them than it is. If the problem is technical and AI can meaningfully change the equation, we are interested.' },
  { q: 'Do you just advise, or do you actually build it?', a: 'We build. Advice without execution is the slow way to be wrong. We will happily audit and strategize, but our core work is designing and shipping the actual systems, and then making sure your team can run them after we leave.' },
  { q: 'Is it safe to let AI into our systems and codebase?', a: "It is, if it is set up correctly, and dangerous if it is not. Most of the horror stories come from giving AI tools broad access with no guardrails, no review gates, and no understanding of the failure modes. Designing that safety layer is one of the things we do best; it is the difference between a multiplier and a liability." },
  { q: 'What does a typical engagement look like?', a: 'Short and intense. A focused diagnosis, a clear architecture with the guardrails defined up front, then a tight build cycle where you see working software within the first couple of weeks. Scope ranges from a single integration to rebuilding how an entire operation runs, and we will size it honestly on the first call.' },
  { q: 'How fast can you start?', a: 'Quickly. We keep deliberate capacity for new engagements, and our AI-native workflow means the gap between "yes" and "working software in front of you" is measured in days and weeks, not quarters.' },
];

function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <section className="section" id="faq" data-screen-label="faq">
      <div className="wrap">
        <div className="section-head reveal">
          <div className="eyebrow">FAQ</div>
          <h2>The questions people ask before they reach out.</h2>
        </div>
        <div className="faq-list reveal">
          {FAQS.map((f, i) => (
            <div className={'faq-item' + (open === i ? ' open' : '')} key={i}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span>{f.q}</span>
                <span className="pm"></span>
              </button>
              <div className="faq-a" style={{ maxHeight: open === i ? 320 : 0 }}>
                <div className="faq-a-inner">{f.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const NEEDS = ['Custom software / SaaS', 'AI integration', 'Claude Code setup', 'Systems consulting', 'Ops automation', 'Not sure yet'];

const STEPS_DEF = [
  { key: 'need',    kind: 'choice',   q: 'What can we help you build?',      hint: 'Pick the closest fit. We’ll get specific on the call.' },
  { key: 'name',    kind: 'text',     q: 'Great. Who are we talking to?',    hint: 'First and last is perfect.', placeholder: 'Your name' },
  { key: 'email',   kind: 'email',    q: 'Where should we reach you?',       hint: 'Goes straight to the partners.', placeholder: 'you@company.com' },
  { key: 'message', kind: 'textarea', q: 'Tell us about the problem.',       hint: 'A few lines is plenty. What you’re trying to build, fix, or figure out.', placeholder: 'We’re trying to…' },
];

function CfStage({ children }) {
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const r = requestAnimationFrame(() => setShown(true));
    return () => cancelAnimationFrame(r);
  }, []);
  return <div className={'cf-stage' + (shown ? ' in' : '')}>{children}</div>;
}

function Contact() {
  const [step, setStep] = useState(0);
  const [form, setForm] = useState({ name: '', email: '', company: '', need: '', message: '' });
  const [err, setErr] = useState('');
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const inputRef = useRef(null);

  const cur = STEPS_DEF[step];
  const total = STEPS_DEF.length;

  useEffect(() => {
    setErr('');
    if (cur && cur.kind !== 'choice' && inputRef.current) {
      const id = setTimeout(() => inputRef.current && inputRef.current.focus(), 60);
      return () => clearTimeout(id);
    }
  }, [step]);

  function valid(k, v) {
    if (k === 'need') return !!v;
    if (k === 'name') return v.trim().length > 1;
    if (k === 'email') return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim());
    if (k === 'message') return v.trim().length > 4;
    return true;
  }

  function next() {
    if (sending) return;
    const v = form[cur.key];
    if (!valid(cur.key, v)) {
      setErr(cur.key === 'email' ? 'That email looks off. Mind checking it?' : 'Just need a little here to continue.');
      return;
    }
    if (step < total - 1) setStep(step + 1);
    else submit();
  }

  async function submit() {
    setSending(true);
    setErr('');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) throw new Error(data.error || 'Something went wrong sending that.');
      setSent(true);
    } catch (e) {
      setErr((e && e.message) || 'Could not send right now. Try again, or email hello@oktra.co.');
    } finally {
      setSending(false);
    }
  }
  function back() { if (step > 0) setStep(step - 1); }

  function onKey(e) {
    if (e.key === 'Enter' && !(cur.kind === 'textarea' && e.shiftKey)) { e.preventDefault(); next(); }
  }

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  return (
    <section className="section contact" id="contact" data-screen-label="contact">
      <div className="wrap">
        <div className="cf-head reveal">
          <div className="eyebrow no-rule">Book a call</div>
          <h2>Let’s see if we’re the right team for it.</h2>
        </div>

        <div className="cf-panel reveal" style={{ '--d': '100ms' }}>

          {sent ? (
            <div className="cf-success">
              <div className="ok-mark"><Check /></div>
              <h3>Message received.</h3>
              <p>Thanks, {form.name.split(' ')[0] || 'there'}. We’ve logged your note about{' '}
                <strong style={{ color: 'var(--fg-2)' }}>{(form.need || 'your project').toLowerCase()}</strong>.{' '}
                One of the partners will reach out at {form.email} within a day.</p>
              <button className="btn btn-ghost" style={{ width: 'fit-content', marginTop: 6 }}
                onClick={() => { setSent(false); setStep(0); setForm({ name: '', email: '', company: '', need: '', message: '' }); }}>
                <span className="label">Start over</span>
              </button>
            </div>
          ) : (
            <React.Fragment>
              <div className="cf-bar" role="presentation">
                {STEPS_DEF.map((s, i) => (
                  <button key={s.key} className={'cf-seg' + (i === step ? ' on' : '') + (i < step ? ' done' : '')}
                    onClick={() => i < step && setStep(i)} aria-label={'Step ' + (i + 1)}>
                    <span></span>
                  </button>
                ))}
                <span className="cf-count mono">{String(step + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}</span>
              </div>

              <CfStage key={step}>
                <h3 className="cf-q">{cur.q}</h3>
                <p className="cf-hint">{cur.hint}</p>

                {cur.kind === 'choice' && (
                  <div className="cf-choices">
                    {NEEDS.map((n) => (
                      <button key={n} className={'cf-choice' + (form.need === n ? ' on' : '')}
                        onClick={() => { set('need', n); setErr(''); setTimeout(() => setStep(1), 180); }}>
                        <span className="cf-choice-dot"></span>{n}
                      </button>
                    ))}
                  </div>
                )}

                {(cur.kind === 'text' || cur.kind === 'email') && (
                  <input ref={inputRef} className="cf-input" type={cur.kind === 'email' ? 'email' : 'text'}
                    value={form[cur.key]} placeholder={cur.placeholder}
                    onChange={(e) => { set(cur.key, e.target.value); setErr(''); }} onKeyDown={onKey} />
                )}

                {cur.kind === 'textarea' && (
                  <textarea ref={inputRef} className="cf-input cf-textarea" value={form.message}
                    placeholder={cur.placeholder}
                    onChange={(e) => { set('message', e.target.value); setErr(''); }} onKeyDown={onKey}></textarea>
                )}

                <div className="cf-err mono">{err}</div>
              </CfStage>

              <div className="cf-foot">
                <button className={'cf-back' + (step === 0 ? ' hidden' : '')} onClick={back}>← Back</button>
                <div className="cf-foot-right">
                  <span className="cf-enter mono">press ↵ enter</span>
                  <button className="btn btn-primary" onClick={next} disabled={sending}>
                    <span className="label">{step === total - 1 ? (sending ? 'Sending…' : 'Send & request call') : 'Continue'} <ArrowUR /></span>
                  </button>
                </div>
              </div>
            </React.Fragment>
          )}
        </div>

        <div className="cf-assure reveal" style={{ '--d': '180ms' }}>
          <span><span className="mono">01</span> Straight to the people who’ll do the work.</span>
          <span><span className="mono">02</span> An honest read, even if AI isn’t the answer.</span>
          <span><span className="mono">03</span> A reply within a day. No funnel, no spam.</span>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer" data-screen-label="footer">
      <div className="wrap">
        <div className="f-brand">
          <span className="brand"><span className="dot"></span>oktra</span>
          <p>An AI-native consulting studio. We design, build, and harden the systems that keep
            you ahead, done the right way.</p>
        </div>
        <div className="f-cols">
          <div className="f-col">
            <span className="h">Studio</span>
            <a onClick={() => scrollToId('services')}>Services</a>
            <a onClick={() => scrollToId('process')}>How we work</a>
            <a onClick={() => scrollToId('approach')}>The right way</a>
            <a onClick={() => scrollToId('work')}>Work</a>
          </div>
          <div className="f-col">
            <span className="h">Connect</span>
            <a onClick={() => scrollToId('contact')}>Book a call</a>
            <a href="mailto:hello@oktra.co">hello@oktra.co</a>
            <a onClick={() => scrollToId('faq')}>FAQ</a>
          </div>
        </div>
      </div>
      <div className="wrap">
        <div className="f-bottom">
          <span>© {new Date().getFullYear()} Oktra Consulting. Placeholder name, pending availability.</span>
          <span>Built AI-native · Top 1% by usage &amp; understanding</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { FAQ, Contact, Footer });
