/* OpSpot — Deal Desk: interactive intake → right-sized package, + pricing tiers. */
const { useState, useEffect, useMemo } = React;

const DD_QUESTIONS = [
  {
    id: 'size', q: 'How big is your team?', hint: 'More people, more inbound to catch.',
    opts: [
      { label: 'Just me', meta: 'solo', s: 0 },
      { label: '2–10', meta: 'small crew', s: 1 },
      { label: '11–50', meta: 'growing', s: 2 },
      { label: '50+', meta: 'multi-location', s: 3 },
    ],
  },
  {
    id: 'value', q: 'What’s a typical job or customer worth?', hint: 'This sets how much each missed touch costs.',
    opts: [
      { label: 'Under $250', meta: 'high volume', s: 0 },
      { label: '$250 – $1,000', meta: 'steady', s: 1 },
      { label: '$1k – $10k', meta: 'real money', s: 2 },
      { label: '$10k+', meta: 'every lead counts', s: 3 },
    ],
  },
  {
    id: 'scope', q: 'How much should disappear off your plate?', hint: 'We can start narrow and grow.',
    opts: [
      { label: 'One nagging workflow', meta: '1 job', s: 0 },
      { label: 'A couple connected ones', meta: '2–3 jobs', s: 1.5 },
      { label: 'Most of the busywork', meta: 'full ops', s: 3 },
    ],
  },
  {
    id: 'urgency', q: 'When do you need this working?', hint: 'Faster installs need more hands on deck.',
    opts: [
      { label: 'I needed it yesterday', meta: 'urgent', s: 2 },
      { label: 'Within a month', meta: 'soon', s: 1 },
      { label: 'Just exploring', meta: 'no rush', s: 0 },
    ],
  },
  {
    id: 'tools', q: 'What do you run today?', hint: 'More tools to connect = more wiring.',
    opts: [
      { label: 'Mostly phone + notebook', meta: 'greenfield', s: 0 },
      { label: 'A couple of tools', meta: 'some stack', s: 1 },
      { label: 'A full CRM / stack to connect', meta: 'integrated', s: 2 },
    ],
  },
  {
    id: 'budget', q: 'What feels comfortable per month?', hint: 'Teller keeps the package honest to this.',
    opts: [
      { label: 'Keep it lean', meta: 'tight', s: 0 },
      { label: 'Some room if it pays back', meta: 'flexible', s: 1.5 },
      { label: 'Whatever earns its keep', meta: 'open', s: 3 },
    ],
  },
];

function recommend(answers) {
  const score = DD_QUESTIONS.reduce((sum, q) => sum + (answers[q.id]?.s ?? 0), 0);
  const budget = answers.budget?.s ?? 0;
  let tierId = score < 5 ? 'starter' : score <= 10 ? 'growth' : 'managed';
  let trimmed = false;
  // Teller affordability guard: lean budget never pushed to top tier.
  if (budget === 0 && tierId === 'managed') { tierId = 'growth'; trimmed = true; }

  const tier = TIERS.find(t => t.id === tierId);
  const valueLabel = (answers.value?.label || '$250 – $1,000');
  const scopeLabel = answers.scope?.label?.toLowerCase() || 'one workflow';
  const urgent = (answers.urgency?.s ?? 0) >= 2;
  const firstWf = answers.scope?.s === 0 ? 'that one workflow' : 'your worst leak';

  const why = [
    { id: 'recon', name: 'Recon', label: 'Value',
      text: `${valueLabel} jobs mean every missed call or cold quote is expensive. I’d size the monthly leak toward the ${tierId === 'managed' ? 'high' : tierId === 'growth' ? 'mid' : 'lower'} end — worth plugging.` },
    { id: 'teller', name: 'Teller', label: 'Affordability',
      text: trimmed
        ? `You asked to stay lean, so I held us to ${tier.price}${tier.per} and a phased start — recovered leakage should clear the fee before you feel it.`
        : `At ${tier.price}${tier.per}, the math works: recovered leakage and saved hours clear the fee with margin to spare. Payback inside month one.` },
    { id: 'orbit', name: 'Orbit', label: 'Strategy',
      text: tierId === 'starter'
        ? `Lock ${firstWf} first, prove the receipt, then we layer the rest once it’s earning. No boiling the ocean.`
        : urgent
          ? `You need speed — we install the core relay now and sequence the rest over the first two weeks.`
          : `Start with the highest-leak workflow, then connect the next two as the receipts roll in.` },
  ];
  return { tier, why, trimmed };
}

function DealDesk({ onClose }) {
  const [step, setStep] = useState(0); // 0..n-1 questions, n = thinking, n+1 = result
  const [answers, setAnswers] = useState({});
  const [thinkOn, setThinkOn] = useState(0);
  const n = DD_QUESTIONS.length;
  const rec = useMemo(() => (step > n ? recommend(answers) : null), [step, answers, n]);

  const pick = (q, opt) => {
    const next = { ...answers, [q.id]: opt };
    setAnswers(next);
    setTimeout(() => {
      if (step < n - 1) setStep(step + 1);
      else setStep(n); // thinking
    }, 180);
  };

  // thinking sequence
  useEffect(() => {
    if (step !== n) return;
    setThinkOn(0);
    const t1 = setTimeout(() => setThinkOn(1), 500);
    const t2 = setTimeout(() => setThinkOn(2), 1150);
    const t3 = setTimeout(() => setThinkOn(3), 1800);
    const t4 = setTimeout(() => setStep(n + 1), 2500);
    return () => [t1, t2, t3, t4].forEach(clearTimeout);
  }, [step, n]);

  const reset = () => { setStep(0); setAnswers({}); };

  const crewMeta = (id) => CREW.find(c => c.id === id) || CREW[0];

  return (
    <section className="section-pad" id="dealdesk" style={{ paddingTop: 110 }}>
      <div className="container">
        <Reveal className="sec-head" style={{ maxWidth: 860 }}>
          <span className="kicker">Pricing · Deal Desk sizes it for you</span>
          <h2 className="display" style={{ marginTop: 14 }}>Tell Deal Desk about your business. Get a right-sized package.</h2>
          <p>No “contact sales for pricing.” Answer six quick questions and Deal Desk recommends the package that fits — using Recon’s value read, Teller’s margin math, and Orbit’s strategy. It will not oversell you.</p>
        </Reveal>

        <div className="dd-wrap">
          <Reveal className="dd-panel">
            <div className="dd-head">
              <div className="dd-av">DD</div>
              <div className="dd-who"><b>Deal Desk</b><small>Package sizing · live</small></div>
              <div className="dd-progress">{step < n ? `${step + 1} / ${n}` : 'done'}</div>
            </div>
            <div className="dd-body">
              {step < n && (
                <React.Fragment>
                  <div className="dd-q">{DD_QUESTIONS[step].q}</div>
                  <div className="dd-hint">{DD_QUESTIONS[step].hint}</div>
                  <div className="dd-options">
                    {DD_QUESTIONS[step].opts.map(opt => {
                      const sel = answers[DD_QUESTIONS[step].id]?.label === opt.label;
                      return (
                        <button key={opt.label} className={`dd-opt ${sel ? 'sel' : ''}`} onClick={() => pick(DD_QUESTIONS[step], opt)}>
                          <span className="dd-dot" />
                          {opt.label}
                          <span className="dd-meta">{opt.meta}</span>
                        </button>
                      );
                    })}
                  </div>
                  <div className="dd-nav">
                    {step > 0 && <button className="dd-back" onClick={() => setStep(step - 1)}>← back</button>}
                  </div>
                </React.Fragment>
              )}

              {step === n && (
                <div className="dd-think">
                  <div className="dd-q" style={{ marginBottom: 8 }}>Sizing your package…</div>
                  {[{ id: 'recon', t: 'Recon is sizing the leak…' }, { id: 'teller', t: 'Teller is running affordability…' }, { id: 'orbit', t: 'Orbit is sequencing the rollout…' }].map((r, i) => {
                    const m = crewMeta(r.id);
                    return (
                      <div key={r.id} className={`tline ${thinkOn > i ? 'on' : ''}`}>
                        <span className="ag" style={{ '--c1': m.c1, '--c2': m.c2 }}><Ico d={crewIcon(r.id)} size={13} /></span>
                        <span><b>{m.name}</b> · {r.t}</span>
                        {thinkOn > i + 0 && thinkOn > i && <span className="ok">✓</span>}
                      </div>
                    );
                  })}
                </div>
              )}

              {step > n && rec && (
                <div className="dd-result">
                  <span className="dd-rec-tier">Recommended for you</span>
                  <div className="dd-rec-name">{rec.tier.name} <span className="dd-rec-price">{rec.tier.price}{rec.tier.per}</span></div>
                  <div className="dd-rec-why">
                    {rec.why.map(w => {
                      const m = crewMeta(w.id);
                      return (
                        <div className="w" key={w.id} style={{ '--c1': m.c1, '--c2': m.c2 }}>
                          <span className="ag">{w.name === 'Deal Desk' ? 'DD' : w.name[0]}</span>
                          <div><b>{w.name} · {w.label}.</b> {w.text}</div>
                        </div>
                      );
                    })}
                  </div>
                  <div className="dd-rec-pay">
                    {rec.trimmed
                      ? <span>Kept lean on purpose. Start narrow, and we scale you up only once the receipts prove it pays.</span>
                      : <span>This is a recommendation, not a hard quote — your free audit confirms the exact <b>net ROI</b> before you commit.</span>}
                  </div>
                  <div className="dd-nav dd-reset">
                    <a href="#contact" className="btn btn-primary" onClick={(e) => { e.preventDefault(); if (onClose) onClose(); scrollToId('contact'); }}>Get this audited free →</a>
                    <button className="dd-back" onClick={reset}>start over</button>
                  </div>
                </div>
              )}
            </div>
          </Reveal>

          <Reveal delay={1} className="tiers">
            {TIERS.map(t => {
              const isRec = rec && rec.tier.id === t.id;
              return (
                <div key={t.id} className={`tier ${t.popular ? 'pop' : ''} ${isRec ? 'rec' : ''}`}>
                  {isRec ? <span className="tier-flag">Deal Desk pick</span> : t.popular ? <span className="tier-flag">Most land here</span> : null}
                  <div className="tier-top">
                    <span className="tier-name">{t.name}</span>
                    <span className="tier-price">{t.price}<span className="per">{t.per}</span></span>
                  </div>
                  <div className="tier-line">{t.line}</div>
                  <div className="tier-fit">{t.fit}</div>
                  <ul className="tier-feats">
                    {t.features.map(f => <li key={f}><Ico d={ICONS.check} size={15} />{f}</li>)}
                  </ul>
                  <div className="tier-crew">
                    {t.crew.map(name => {
                      const m = CREW.find(c => c.name === name) || CREW[0];
                      return <span className="cc" key={name} style={{ '--c1': m.c1, '--c2': m.c2 }} title={name}>{name === 'Deal Desk' ? 'DD' : name[0]}</span>;
                    })}
                  </div>
                </div>
              );
            })}
            <p className="note-illus" style={{ marginTop: 4 }}>Placeholder pricing. Custom enterprise / partner pricing above Full Managed.</p>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function PricingOverlay({ open, onClose }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="pricing-overlay" onClick={(e) => { if (e.target.classList.contains('pricing-overlay')) onClose(); }}>
      <button className="pricing-close" onClick={onClose} aria-label="Close pricing"><Ico d={ICONS.x} size={20} /></button>
      <div className="pricing-sheet">
        <DealDesk onClose={onClose} />
      </div>
    </div>
  );
}

Object.assign(window, { DD_QUESTIONS, recommend, DealDesk, PricingOverlay });
