// demo-wizard.jsx: Strata "Book a Demo" conversational wizard.

const { useState, useRef, useEffect } = React;

const Check = ({ s = 13 }) =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" aria-hidden="true">
    <path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" />
  </svg>;

/* Step definitions ---------------------------------------------------------- */
const STEPS = [
  {
    key: 'role',
    type: 'single',
    q: 'What\u2019s your role?',
    options: ['CFO', 'COO', 'Managing Partner', 'Innovation or Operations', 'Billing or Revenue', 'Other'],
  },
  {
    key: 'size',
    type: 'single',
    q: 'How big is your firm?',
    options: ['Under 100 attorneys', '100 to 300 attorneys', '300+ attorneys'],
  },
  {
    key: 'firmType',
    type: 'multi',
    q: 'What type of firm?',
    hint: 'Select all that apply.',
    options: ['Insurance defense', 'General litigation', 'Personal injury or plaintiff', 'Real estate and title', 'Corporate or transactional', 'Labor and employment', 'Family law', 'General or full-service practice', 'Other'],
  },
  {
    key: 'timeSinks',
    type: 'multi',
    q: 'What\u2019s eating your team\u2019s time?',
    hint: 'Select all that apply.',
    options: ['Invoice appeals', 'Matter intake and opening', 'Conflicts checks and new-client setup', 'Billing follow-up and collections', 'Trust accounting and reconciliation', 'Lateral onboarding', 'Back office (AR/AP/payroll)', 'Records and document management', 'Other'],
  },
  {
    key: 'outsource',
    type: 'single-followup',
    q: 'Do you outsource any of this today?',
    options: ['Yes, an offshore team or outsourcing provider', 'In-house only', 'Not sure'],
    followIf: 'Yes, an offshore team or outsourcing provider',
    follow: {
      key: 'spend',
      q: 'Roughly how much do you spend on it annually?',
      hint: 'Optional. This step is skippable.',
      options: ['Under $250K', '$250K to $1M', '$1M+', 'Prefer not to say'],
    },
  },
  {
    key: 'contact',
    type: 'contact',
    q: 'Where should we send your demo details?',
    hint: 'This is the only step that collects contact info.',
  },
];

const RECAP_LABELS = {
  role: 'Role',
  size: 'Firm size',
  firmType: 'Firm type',
  timeSinks: 'Time sinks',
  outsource: 'Outsourcing',
  spend: 'Annual spend',
  name: 'Name',
  email: 'Work email',
  firmName: 'Firm',
  notes: 'Notes',
};

/* Where completed demo requests are sent. */
const DEMO_RECIPIENT = 'hello@strata.ai';
/* Submissions are POSTed here. Set this to your Google Apps Script Web App URL
 * (it ends in /exec). The script receives the JSON and emails each submission
 * to DEMO_RECIPIENT from your own Workspace account. */
const DEMO_ENDPOINT = 'https://script.google.com/macros/s/AKfycbyxOO14JvZn2WeDYGsXP8YLOHadziVfipxOM8kP-kziutFrVmdgcquNiby6HiHfZ9mA/exec';
const RECAP_ORDER = ['role', 'size', 'firmType', 'timeSinks', 'outsource', 'spend', 'name', 'email', 'firmName', 'notes'];

function hasValue(v) {
  return Array.isArray(v) ? v.length > 0 : Boolean(v && String(v).trim());
}

/* Flatten answers into a labelled, email-friendly payload. */
function buildPayload(answers) {
  const fmt = (v) => Array.isArray(v) ? v.join(', ') : String(v).trim();
  const payload = {
    _subject: buildSubject(answers),
  };
  RECAP_ORDER.forEach((k) => {
    if (hasValue(answers[k])) payload[RECAP_LABELS[k]] = fmt(answers[k]);
  });
  return payload;
}

/* Subject line: name + firm, so every lead is its own inbox thread. */
function buildSubject(answers) {
  const name = answers.name.trim();
  const firm = answers.firmName.trim();
  if (name && firm) return 'Demo request: ' + name + ' · ' + firm;
  if (name) return 'Demo request: ' + name;
  if (firm) return 'Demo request: ' + firm;
  return 'Demo request: New firm';
}

/* mailto fallback, used only if the network submission fails. */
function buildMailto(answers) {
  const fmt = (v) => Array.isArray(v) ? v.join(', ') : String(v).trim();
  const lines = RECAP_ORDER
    .filter((k) => hasValue(answers[k]))
    .map((k) => RECAP_LABELS[k] + ': ' + fmt(answers[k]));
  const subject = 'Demo request: ' + (answers.firmName.trim() || 'New firm');
  const body = [
    'New demo request from the Strata site.',
    '',
    ...lines,
  ].join('\n');
  return 'mailto:' + DEMO_RECIPIENT +
    '?subject=' + encodeURIComponent(subject) +
    '&body=' + encodeURIComponent(body);
}

function Wizard() {
  const [step, setStep] = useState(0);
  const [done, setDone] = useState(false);
  const [answers, setAnswers] = useState({
    role: '', size: '', firmType: [], timeSinks: [], outsource: '', spend: '',
    name: '', email: '', firmName: '', notes: '',
  });
  const stageRef = useRef(null);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState(false);

  const set = (k, v) => setAnswers((a) => ({ ...a, [k]: v }));
  const total = STEPS.length;
  const def = STEPS[step];

  // Reset scroll to top of stage on step change.
  useEffect(() => { if (stageRef.current) stageRef.current.scrollTop = 0; }, [step, done]);

  const advance = () => {
    if (step < total - 1) setStep((s) => s + 1);
  };
  const back = () => setStep((s) => Math.max(0, s - 1));

  // Submit: open the visitor's email client addressed to the demo inbox,
  // Submit: POST the full qualification to the Apps Script endpoint, which
  // emails it to DEMO_RECIPIENT. No email client is opened. Apps Script web
  // apps don't return CORS headers, so we POST as a simple text/plain request
  // in no-cors mode (the script still receives the body) and treat a resolved
  // request as success. On network failure, surface an error with a mailto
  // fallback so a lead is never silently lost.
  const submit = async () => {
    setError(false);
    setSending(true);
    try {
      if (DEMO_ENDPOINT.indexOf('PASTE_') !== -1) throw new Error('Endpoint not configured');
      await fetch(DEMO_ENDPOINT, {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'text/plain;charset=utf-8' },
        body: JSON.stringify(buildPayload(answers)),
      });
      setDone(true);
    } catch (e) {
      setError(true);
    } finally {
      setSending(false);
    }
  };

  // Single-select: record + auto-advance after a brief beat so the tick registers.
  const pickSingle = (k, val) => {
    set(k, val);
    setTimeout(advance, 260);
  };

  const toggleMulti = (k, val) => {
    setAnswers((a) => {
      const cur = a[k];
      return { ...a, [k]: cur.includes(val) ? cur.filter((x) => x !== val) : [...cur, val] };
    });
  };

  const progressPct = done ? 100 : Math.round(((step + 1) / total) * 100);

  if (done) return <Confirmation answers={answers} />;

  return (
    <div className="wizard-wrap">
      <div className="progress"><div className="progress-fill" style={{ width: progressPct + '%' }} /></div>
      <div className="wizard-stage" ref={stageRef}>
        <div className="wizard-col">
          <div className="step-anim" key={step}>
            <div className="step-count">
              <span>{String(step + 1).padStart(2, '0')}</span>
              <span className="bar" />
              <span>{String(total).padStart(2, '0')}</span>
            </div>
            <h1 className="step-q">{def.q}</h1>
            {def.hint && <p className="step-hint">{def.hint}</p>}

            {def.type === 'single' &&
              <SingleStep def={def} value={answers[def.key]} onPick={(v) => pickSingle(def.key, v)} />}

            {def.type === 'single-followup' &&
              <FollowupStep
                def={def}
                value={answers[def.key]}
                followValue={answers[def.follow.key]}
                onPick={(v) => {
                  set(def.key, v);
                  if (v !== def.followIf) { set(def.follow.key, ''); setTimeout(advance, 260); }
                }}
                onPickFollow={(v) => set(def.follow.key, v)}
              />}

            {def.type === 'multi' &&
              <MultiStep def={def} value={answers[def.key]} onToggle={(v) => toggleMulti(def.key, v)} />}

            {def.type === 'contact' &&
              <ContactStep answers={answers} set={set} />}

            {def.type === 'contact' && error &&
              <p className="submit-error">
                We couldn’t send your details just now. Please try again, or email{' '}
                <a href={buildMailto(answers)}>{DEMO_RECIPIENT}</a> directly.
              </p>}

            <StepControls
              def={def}
              step={step}
              answers={answers}
              onBack={back}
              onNext={advance}
              onSkip={() => { set(def.follow ? def.follow.key : '', ''); advance(); }}
              onSubmit={submit}
              sending={sending}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

/* Steps --------------------------------------------------------------------- */
function SingleStep({ def, value, onPick }) {
  return (
    <div className="options">
      {def.options.map((opt) =>
        <button key={opt} type="button"
          className={'option' + (value === opt ? ' selected' : '')}
          onClick={() => onPick(opt)}>
          <span className="marker"><Check /></span>
          <span className="opt-label">{opt}</span>
        </button>
      )}
    </div>
  );
}

function MultiStep({ def, value, onToggle }) {
  return (
    <div className="options">
      {def.options.map((opt) =>
        <button key={opt} type="button"
          className={'option multi' + (value.includes(opt) ? ' selected' : '')}
          onClick={() => onToggle(opt)}>
          <span className="marker"><Check /></span>
          <span className="opt-label">{opt}</span>
        </button>
      )}
    </div>
  );
}

function FollowupStep({ def, value, followValue, onPick, onPickFollow }) {
  const showFollow = value === def.followIf;
  return (
    <React.Fragment>
      <div className="options">
        {def.options.map((opt) =>
          <button key={opt} type="button"
            className={'option' + (value === opt ? ' selected' : '')}
            onClick={() => onPick(opt)}>
            <span className="marker"><Check /></span>
            <span className="opt-label">{opt}</span>
          </button>
        )}
      </div>
      {showFollow &&
        <div className="followup step-anim">
          <p className="followup-q">{def.follow.q}</p>
          <p className="followup-hint">{def.follow.hint}</p>
          <div className="chip-row">
            {def.follow.options.map((opt) =>
              <button key={opt} type="button"
                className={'chip' + (followValue === opt ? ' selected' : '')}
                onClick={() => onPickFollow(followValue === opt ? '' : opt)}>
                {opt}
              </button>
            )}
          </div>
        </div>}
    </React.Fragment>
  );
}

function ContactStep({ answers, set }) {
  return (
    <div className="fields">
      <div className="field">
        <label>Name</label>
        <input type="text" value={answers.name} placeholder="Your name"
          onChange={(e) => set('name', e.target.value)} />
      </div>
      <div className="field">
        <label>Work email</label>
        <input type="email" value={answers.email} placeholder="you@firm.com"
          onChange={(e) => set('email', e.target.value)} />
      </div>
      <div className="field">
        <label>Firm name</label>
        <input type="text" value={answers.firmName} placeholder="Your firm"
          onChange={(e) => set('firmName', e.target.value)} />
      </div>
      <div className="field">
        <label>Anything else we should know? <span className="opt">(optional)</span></label>
        <textarea value={answers.notes} placeholder="Context that would make your demo sharper."
          onChange={(e) => set('notes', e.target.value)} />
      </div>
    </div>
  );
}

/* Footer controls ----------------------------------------------------------- */
function StepControls({ def, step, answers, onBack, onNext, onSkip, onSubmit, sending }) {
  const isMulti = def.type === 'multi';
  const isFollow = def.type === 'single-followup';
  const isContact = def.type === 'contact';
  const showFollowSelected = isFollow && answers[def.key] === def.followIf;

  const emailOk = /.+@.+\..+/.test(answers.email.trim());
  const contactReady = answers.name.trim() && emailOk && answers.firmName.trim();

  return (
    <div className="step-controls">
      {step > 0
        ? <button type="button" className="btn-text" onClick={onBack}>← Back</button>
        : <span />}
      <div className="spacer" />
      <div className="right">
        {/* Skippable follow-up step */}
        {showFollowSelected &&
          <button type="button" className="btn-text" onClick={onSkip}>Skip</button>}
        {isMulti &&
          <button type="button" className="btn btn-primary"
            disabled={answers[def.key].length === 0} onClick={onNext}>Next</button>}
        {showFollowSelected &&
          <button type="button" className="btn btn-primary" onClick={onNext}>Next</button>}
        {isContact &&
          <button type="button" className="btn btn-primary" disabled={!contactReady || sending} onClick={onSubmit}>
            {sending ? 'Sending…' : 'Request demo'}
          </button>}
      </div>
    </div>
  );
}

/* Confirmation -------------------------------------------------------------- */
function Confirmation({ answers }) {
  const fmt = (v) => Array.isArray(v) ? (v.length ? v.join(', ') : '\u2014') : (v && String(v).trim() ? v : '\u2014');
  const rows = RECAP_ORDER.filter((k) => hasValue(answers[k]));

  return (
    <div className="wizard-wrap">
      <div className="progress"><div className="progress-fill" style={{ width: '100%' }} /></div>
      <div className="wizard-stage">
        <div className="confirm">
          <div className="confirm-mark"><Check s={24} /></div>
          <h1>Thanks. Your demo will be built around what you told us.</h1>
          <p>Your details are on their way to our team. We’ll be in touch shortly to set it up. No generic walkthrough: we’ll come ready to talk about the work your firm is writing off today.</p>

          <div className="recap">
            <div className="recap-head">What we’ll bring to your demo</div>
            {rows.map((k) =>
              <div className="recap-row" key={k}>
                <span className="k">{RECAP_LABELS[k]}</span>
                <span className="v">{fmt(answers[k])}</span>
              </div>
            )}
          </div>

          <a href="index.html" className="btn btn-ghost">← Back to Strata</a>
        </div>
      </div>
    </div>
  );
}

/* Mount --------------------------------------------------------------------- */
function DemoPage() {
  return (
    <React.Fragment>
      <nav className="demo-nav">
        <div className="container demo-nav-inner">
          <a href="index.html" className="wordmark" aria-label="Strata home">
            <img src="assets/strata-logo.svg" alt="Strata" className="wordmark-full" />
          </a>
          <a href="index.html" className="back">Back to site</a>
        </div>
      </nav>
      <Intro />
      <Wizard />
    </React.Fragment>
  );
}

function Intro() {
  return (
    <div className="container" style={{ paddingTop: 'clamp(48px, 8vh, 88px)', paddingBottom: 0, maxWidth: 760 }}>
      <div className="eyebrow" style={{ marginBottom: 16 }}>Book a Demo</div>
      <h1 style={{
        fontSize: 'clamp(34px, 5vw, 60px)', fontWeight: 500, letterSpacing: '-0.028em',
        lineHeight: 1.04, margin: '0 0 18px', textWrap: 'balance',
      }}>
        A demo shaped by your firm, not a generic tour.
      </h1>
      <p style={{ fontSize: 'clamp(18px, 1.7vw, 21px)', color: 'var(--muted)', margin: 0, maxWidth: '52ch' }}>
        A few quick questions so your demo is built around how your firm actually works.
      </p>
    </div>
  );
}

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