// HiLooks live-prototype flows: every CTA opens a real multi-step modal.
// Owned by Anvul Ltd. Operated under licence by HiLooks. Demo build.

// ============================================================================
// STEP COMPONENTS — small primitives the flow engine renders per step
// ============================================================================

const FlowText = ({ label, helper, placeholder, value, onChange, type = 'text', autoFocus = true }) => (
  <div className="flow-step">
    <label className="flow-label">{label}</label>
    {helper && <div className="flow-helper">{helper}</div>}
    <input
      className="flow-input"
      type={type}
      autoFocus={autoFocus}
      value={value || ''}
      placeholder={placeholder}
      onChange={(e) => onChange(type === 'text' && label.toLowerCase().includes('postcode') ? e.target.value.toUpperCase() : e.target.value)}
    />
  </div>
);

const FlowPills = ({ label, helper, options, value, onChange, multi = false }) => {
  const selected = multi ? (value || []) : value;
  const toggle = (id) => {
    if (multi) {
      const set = new Set(selected);
      set.has(id) ? set.delete(id) : set.add(id);
      onChange([...set]);
    } else onChange(id);
  };
  const isOn = (id) => multi ? (selected || []).includes(id) : selected === id;
  return (
    <div className="flow-step">
      <label className="flow-label">{label}</label>
      {helper && <div className="flow-helper">{helper}</div>}
      <div className="flow-pills">
        {options.map(o => (
          <button
            key={o.id}
            className={`flow-pill ${isOn(o.id) ? 'active' : ''}`}
            onClick={() => toggle(o.id)}
          >{o.l}</button>
        ))}
      </div>
    </div>
  );
};

const FlowTextarea = ({ label, helper, placeholder, value, onChange, rows = 4 }) => (
  <div className="flow-step">
    <label className="flow-label">{label}</label>
    {helper && <div className="flow-helper">{helper}</div>}
    <textarea
      className="flow-input flow-textarea"
      autoFocus
      rows={rows}
      value={value || ''}
      placeholder={placeholder}
      onChange={(e) => onChange(e.target.value)}
    />
  </div>
);

const FlowDouble = ({ label, helper, fields, value, onChange }) => {
  const v = value || {};
  return (
    <div className="flow-step">
      <label className="flow-label">{label}</label>
      {helper && <div className="flow-helper">{helper}</div>}
      <div className="flow-double">
        {fields.map(f => (
          <input
            key={f.id}
            className="flow-input"
            type={f.type || 'text'}
            value={v[f.id] || ''}
            placeholder={f.placeholder}
            onChange={(e) => onChange({ ...v, [f.id]: e.target.value })}
          />
        ))}
      </div>
    </div>
  );
};

const FlowFundingChoice = ({ label, helper, value, onChange }) => (
  <div className="flow-step">
    <label className="flow-label">{label}</label>
    {helper && <div className="flow-helper">{helper}</div>}
    <div className="flow-funding-grid">
      <button
        type="button"
        className={`flow-funding-card ${value === 'self' ? 'active' : ''}`}
        onClick={() => onChange('self')}
      >
        <div className="flow-funding-tag">OPTION A</div>
        <div className="flow-funding-num">£3,500</div>
        <div className="flow-funding-sub">paid up front</div>
        <div className="flow-funding-desc">No tie-in. No recoupment. Walk in clean.</div>
      </button>
      <button
        type="button"
        className={`flow-funding-card accent ${value === 'deferred' ? 'active' : ''}`}
        onClick={() => onChange('deferred')}
      >
        <div className="flow-funding-tag">OPTION B · SECRET WEAPON</div>
        <div className="flow-funding-num">£0</div>
        <div className="flow-funding-sub">up front</div>
        <div className="flow-funding-desc">Settled via 24 installs · £150 credit each. You work with us.</div>
      </button>
    </div>
  </div>
);

// ============================================================================
// PROGRESS + CONFIRM screens
// ============================================================================

const FlowProgress = ({ current, total }) => (
  <div className="flow-progress">
    {Array.from({ length: total }, (_, i) => (
      <span key={i} className={`flow-progress-dot ${i <= current ? 'on' : ''}`} />
    ))}
  </div>
);

const FlowConfirm = ({ result, onClose }) => (
  <div className="flow-confirm">
    <div className="flow-confirm-tick">
      <svg viewBox="0 0 48 48" fill="none">
        <circle cx="24" cy="24" r="22" stroke="currentColor" strokeWidth="1.5" opacity="0.4" />
        <path d="M14 24 L21 31 L34 17" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    </div>
    <div className="flow-confirm-title">{result.title}</div>
    {result.ref && (
      <div className="flow-confirm-ref">{result.ref}</div>
    )}
    <p className="flow-confirm-body">{result.body}</p>
    {result.meta && result.meta.length > 0 && (
      <div className="flow-confirm-meta">
        {result.meta.map(([k, v], i) => (
          <div key={i} className="flow-confirm-row">
            <span>{k}</span><span className="mono">{v}</span>
          </div>
        ))}
      </div>
    )}
    {result.next && (
      <div className="flow-confirm-next">
        <div className="flow-confirm-next-label">WHAT HAPPENS NEXT</div>
        <ol>{result.next.map((n, i) => <li key={i}>{n}</li>)}</ol>
      </div>
    )}
    <button className="btn btn-accent" style={{ width: '100%', justifyContent: 'center', marginTop: 20 }} onClick={onClose}>
      Done
    </button>
  </div>
);

// ============================================================================
// FLOW MODAL — orchestrates steps + confirm screen
// ============================================================================

const FlowModal = ({ flowDef, prefill, onClose }) => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState(prefill || {});
  const [done, setDone] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    document.body.classList.add('flow-open');
    return () => document.body.classList.remove('flow-open');
  }, []);

  const stepDef = flowDef.steps[step];
  const isLast = step === flowDef.steps.length - 1;

  const value = stepDef ? data[stepDef.field] : null;
  const validate = stepDef && stepDef.validate ? stepDef.validate : (v) => !!v && (typeof v !== 'string' || v.trim().length > 0);
  const valid = !stepDef || validate(value, data);

  const update = (v) => setData({ ...data, [stepDef.field]: v });

  const next = () => {
    if (!valid) return;
    if (isLast) {
      setSubmitting(true);
      setTimeout(() => {
        setDone(flowDef.onSubmit(data));
        setSubmitting(false);
      }, 700);
    } else {
      setStep(step + 1);
    }
  };
  const back = () => setStep(Math.max(0, step - 1));

  return (
    <div className="flow-overlay" onClick={onClose}>
      <div className="flow-card" onClick={(e) => e.stopPropagation()}>
        <button className="flow-close" onClick={onClose} aria-label="Close">×</button>

        {!done ? (
          <>
            <div className="flow-header">
              <div className="flow-eyebrow">{flowDef.eyebrow}</div>
              <h2 className="flow-title">{flowDef.title}</h2>
              {flowDef.subtitle && <p className="flow-subtitle">{flowDef.subtitle}</p>}
            </div>
            <FlowProgress current={step} total={flowDef.steps.length} />
            <div className="flow-body">
              {stepDef && stepDef.component({
                ...stepDef.props,
                value,
                onChange: update,
              })}
            </div>
            <div className="flow-actions">
              {step > 0 && (
                <button className="btn btn-ghost" onClick={back} disabled={submitting}>← Back</button>
              )}
              <div style={{ flex: 1 }} />
              <button
                className="btn btn-accent"
                disabled={!valid || submitting}
                onClick={next}
              >
                {submitting ? 'Submitting…' : (isLast ? (flowDef.submitLabel || 'Submit') : 'Next')} <span className="arrow">→</span>
              </button>
            </div>
            <div className="flow-step-indicator">
              Step {step + 1} of {flowDef.steps.length}
            </div>
          </>
        ) : (
          <FlowConfirm result={done} onClose={onClose} />
        )}
      </div>
    </div>
  );
};

// ============================================================================
// FLOW HOST — global mount, listens for window.openFlow
// ============================================================================

const FlowHost = () => {
  const [active, setActive] = React.useState(null);

  React.useEffect(() => {
    window.openFlow = (name, prefill = {}) => {
      if (FLOWS[name]) setActive({ name, prefill });
    };
    window.closeFlow = () => setActive(null);
    const esc = (e) => { if (e.key === 'Escape') setActive(null); };
    window.addEventListener('keydown', esc);
    return () => window.removeEventListener('keydown', esc);
  }, []);

  if (!active) return null;
  return <FlowModal flowDef={FLOWS[active.name]} prefill={active.prefill} onClose={() => setActive(null)} />;
};

// ============================================================================
// FLOW DEFINITIONS — the actual product flows
// ============================================================================

const cap = (s) => s ? s.charAt(0).toUpperCase() + s.slice(1).replace(/[-_]/g, ' ') : '—';
const ref = (prefix, base) => prefix + '-' + (base + Math.floor(Math.random() * 200));

const FLOWS = {
  // ---------- HOMEOWNER: Quote / Survey booking ----------
  quote: {
    eyebrow: 'GET A FIXED QUOTE',
    title: 'Book your free survey',
    subtitle: 'Five questions. Eight minutes. We reply within four working hours.',
    submitLabel: 'Book my survey',
    steps: [
      {
        field: 'postcode',
        component: FlowText,
        props: { label: 'Your postcode', placeholder: 'e.g. DE22 2HP', helper: 'We work across Derby, Nottingham and Sheffield.' },
        validate: (v) => v && v.replace(/\s/g, '').length >= 5,
      },
      {
        field: 'house',
        component: FlowPills,
        props: {
          label: 'What kind of house?',
          helper: 'Pick the closest match. We size precisely on the survey itself.',
          options: [
            { id: 'flat', l: 'Flat' },
            { id: 'terrace', l: 'Terrace' },
            { id: 'semi', l: 'Semi-detached' },
            { id: 'detached', l: 'Detached' },
            { id: 'bungalow', l: 'Bungalow' },
          ],
        },
      },
      {
        field: 'year',
        component: FlowPills,
        props: {
          label: 'When was it built?',
          options: [
            { id: 'pre-1930', l: 'Pre-1930' },
            { id: '1930-1980', l: '1930–1980' },
            { id: '1980-2000', l: '1980–2000' },
            { id: 'post-2000', l: 'Post-2000' },
          ],
        },
      },
      {
        field: 'insulation',
        component: FlowPills,
        props: {
          label: 'How insulated?',
          helper: 'Honest guess is fine — we measure on the day.',
          options: [
            { id: 'poor', l: 'Poor' },
            { id: 'average', l: 'Average' },
            { id: 'good', l: 'Good' },
          ],
        },
      },
      {
        field: 'contact',
        component: FlowDouble,
        props: {
          label: 'How should we reach you?',
          helper: 'A real engineer calls you within four working hours.',
          fields: [
            { id: 'name', placeholder: 'Your name' },
            { id: 'email', type: 'email', placeholder: 'Your email' },
          ],
        },
        validate: (v) => v && v.name && v.email && /@/.test(v.email),
      },
    ],
    onSubmit: (data) => ({
      title: 'Survey booked.',
      ref: ref('AVL', 3120),
      body: `Thanks${data.contact && data.contact.name ? ', ' + data.contact.name.split(' ')[0] : ''}. An MCS-certified engineer will call you within four working hours to lock in a 90-minute room-by-room survey.`,
      meta: [
        ['Postcode', data.postcode || '—'],
        ['Property', `${cap(data.house)} · ${data.year || '—'}`],
        ['Insulation', cap(data.insulation)],
        ['Email', (data.contact && data.contact.email) || '—'],
        ['Reply ETA', '< 4 working hours'],
      ],
      next: [
        'We confirm a survey slot by phone (≈10 min call).',
        'On survey day: 90 mins, room-by-room heat-loss, photos, U-values.',
        'Within 7 days: a fixed quote with BUS-grant pre-applied. No salesman, no pressure.',
      ],
    }),
  },

  // ---------- HOMEOWNER: Email me this quote (savings calc) ----------
  emailQuote: {
    eyebrow: 'EMAIL YOUR ESTIMATE',
    title: 'Send me this saving',
    subtitle: 'PDF with full assumptions, no marketing follow-up unless you ask.',
    submitLabel: 'Email it to me',
    steps: [
      {
        field: 'email',
        component: FlowText,
        props: { label: 'Where shall we send it?', type: 'email', placeholder: 'you@example.com', helper: 'Single email, no spam list. Promise.' },
        validate: (v) => v && /@/.test(v),
      },
    ],
    onSubmit: (data) => ({
      title: 'PDF sent.',
      body: `Quote summary on its way to ${data.email}. Look in your inbox in the next minute or two — sometimes spam folder, sorry.`,
      meta: [
        ['Sent to', data.email],
        ['Includes', 'Heat demand, running cost, install, BUS grant, payback'],
      ],
    }),
  },

  // ---------- HOMEOWNER: WhatsApp / call ----------
  whatsapp: {
    eyebrow: 'CHAT TO HiLOOKS',
    title: 'Say hi on WhatsApp',
    subtitle: 'A real engineer reads it. Reply within an hour during work hours.',
    submitLabel: 'Send to WhatsApp',
    steps: [
      {
        field: 'topic',
        component: FlowPills,
        props: {
          label: 'What do you want to chat about?',
          options: [
            { id: 'quote', l: 'Get a quote' },
            { id: 'sizing', l: 'Will it heat my house?' },
            { id: 'finance', l: 'Finance / £0 upfront' },
            { id: 'noise', l: 'How loud is it?' },
            { id: 'other', l: 'Something else' },
          ],
        },
      },
      {
        field: 'message',
        component: FlowTextarea,
        props: {
          label: 'Your message',
          placeholder: "e.g. We're a 1972 semi in Allestree. Currently on a combi boiler. Wondering whether a heat pump would actually heat the upstairs properly…",
          rows: 5,
        },
        validate: (v) => v && v.trim().length >= 10,
      },
      {
        field: 'phone',
        component: FlowText,
        props: { label: 'Your mobile (for WhatsApp)', placeholder: '07…', type: 'tel', helper: 'We only text you back. No call-centres, no autodialers.' },
        validate: (v) => v && v.replace(/\D/g, '').length >= 10,
      },
    ],
    onSubmit: (data) => ({
      title: 'Message queued.',
      body: 'A HiLooks engineer will WhatsApp you within an hour during working hours (Mon–Fri 8am–6pm). After hours, first thing next morning.',
      meta: [
        ['Topic', cap(data.topic)],
        ['Mobile', data.phone],
        ['Hours', 'Mon–Fri 8am–6pm'],
      ],
    }),
  },

  // ---------- ENGINEER: Partner network application ----------
  partnerApply: {
    eyebrow: 'PARTNER APPLICATION',
    title: 'Apply to join the HiLooks network',
    subtitle: 'Eight minutes. We onboard 2–3 firms per region per year. We reply within four working hours.',
    submitLabel: 'Submit application',
    steps: [
      {
        field: 'firm',
        component: FlowDouble,
        props: {
          label: 'Your firm',
          helper: 'We contract firm-to-firm. Limited company or sole trader with a registered business name.',
          fields: [
            { id: 'name', placeholder: 'Firm / trading name' },
            { id: 'ch', placeholder: 'Companies House no. (or VAT no.)' },
          ],
        },
        validate: (v) => v && v.name && v.name.trim().length >= 2,
      },
      {
        field: 'region',
        component: FlowPills,
        props: {
          label: 'Where do you mostly work?',
          helper: "Pick the area closest to your depot. We onboard one region at a time.",
          options: [
            { id: 'derby', l: 'Derby + Derbyshire' },
            { id: 'notts', l: 'Nottingham + Notts' },
            { id: 'sheffield', l: 'Sheffield + S. Yorks' },
            { id: 'other', l: 'Other UK' },
          ],
        },
      },
      {
        field: 'capacity',
        component: FlowDouble,
        props: {
          label: 'Capacity',
          fields: [
            { id: 'engineers', type: 'number', placeholder: 'Engineers (incl. you)' },
            { id: 'mcs', placeholder: 'MCS membership no.' },
          ],
        },
        validate: (v) => v && v.engineers && Number(v.engineers) >= 1,
      },
      {
        field: 'experience',
        component: FlowPills,
        props: {
          label: 'How many heat-pump installs in the last 12 months?',
          options: [
            { id: '0', l: '0 — new to heat pumps' },
            { id: '1-10', l: '1 — 10' },
            { id: '11-30', l: '11 — 30' },
            { id: '31-100', l: '31 — 100' },
            { id: '100+', l: '100+' },
          ],
        },
      },
      {
        field: 'funding',
        component: FlowFundingChoice,
        props: {
          label: 'If you need training, which funding route?',
          helper: 'Skip if your firm is already MCS-certified — both options are about how trainee firms enter the network.',
        },
        validate: () => true,
      },
      {
        field: 'contact',
        component: FlowDouble,
        props: {
          label: 'How should we reach you?',
          fields: [
            { id: 'name', placeholder: 'Your name' },
            { id: 'email', type: 'email', placeholder: 'Your email' },
          ],
        },
        validate: (v) => v && v.name && v.email && /@/.test(v.email),
      },
    ],
    onSubmit: (data) => ({
      title: 'Application received.',
      ref: ref('HL-PARTNER', 240),
      body: `Thanks${data.contact && data.contact.name ? ', ' + data.contact.name.split(' ')[0] : ''}. A partner manager (likely Sarah K) will call within four working hours to walk through the network and answer questions before any paperwork.`,
      meta: [
        ['Firm', (data.firm && data.firm.name) || '—'],
        ['Region', cap(data.region)],
        ['Engineers', (data.capacity && data.capacity.engineers) || '—'],
        ['Recent installs', cap(data.experience)],
        ['Funding (if training)', data.funding === 'self' ? 'Self-funded · £3,500' : data.funding === 'deferred' ? 'Deferred-fee · £0 up front' : '—'],
        ['Email', (data.contact && data.contact.email) || '—'],
      ],
      next: [
        'Partner-manager call (≈25 min) — Sarah K explains the rate card, tier ladder, weekly pay run.',
        'You receive a partner pack: contract template, MCS handoff spec, parts kit lead-time, brand guidelines.',
        'First trial install within 30 days. Bronze tier from week one. Climb on quality + flow.',
      ],
    }),
  },

  // ---------- ENGINEER: Cohort 04 / Academy application ----------
  cohortApply: {
    eyebrow: 'COHORT 04 · 15 APR 2027',
    title: 'Apply for HiLooks Academy',
    subtitle: 'Eight-week MCS heat-pump install course. 8 places per cohort. Selection is rigorous.',
    submitLabel: 'Submit application',
    steps: [
      {
        field: 'background',
        component: FlowPills,
        props: {
          label: 'Where are you starting from?',
          options: [
            { id: 'gas', l: 'Gas Safe engineer' },
            { id: 'plumber', l: 'Plumber' },
            { id: 'electrician', l: 'Electrician' },
            { id: 'mcs', l: 'Already MCS — partner straight in' },
            { id: 'changer', l: 'Career changer (no trade yet)' },
          ],
        },
      },
      {
        field: 'years',
        component: FlowPills,
        props: {
          label: 'Years in your current trade',
          options: [
            { id: '0-2', l: '0 — 2 years' },
            { id: '3-5', l: '3 — 5 years' },
            { id: '6-10', l: '6 — 10 years' },
            { id: '10+', l: '10+ years' },
            { id: 'na', l: 'N/A — career changer' },
          ],
        },
      },
      {
        field: 'funding',
        component: FlowFundingChoice,
        props: {
          label: 'How will you fund the £3,500 fee?',
          helper: 'Both routes are real. Pick what works. The deferred-fee option is what most career changers use.',
        },
        validate: (v) => v === 'self' || v === 'deferred',
      },
      {
        field: 'why',
        component: FlowTextarea,
        props: {
          label: 'Why heat pumps, and why now?',
          placeholder: "Two or three honest sentences. We read these — selection is rigorous and we look for genuine motivation, not buzzwords.",
          rows: 4,
        },
        validate: (v) => v && v.trim().length >= 30,
      },
      {
        field: 'contact',
        component: FlowDouble,
        props: {
          label: 'Contact details',
          helper: '£100 application fee taken at interview, fully refunded on course completion.',
          fields: [
            { id: 'name', placeholder: 'Your full name' },
            { id: 'email', type: 'email', placeholder: 'Email' },
          ],
        },
        validate: (v) => v && v.name && v.email && /@/.test(v.email),
      },
    ],
    onSubmit: (data) => ({
      title: 'Application received.',
      ref: ref('HL-COHORT04', 60),
      body: `Cohort 04 starts 15 Apr 2027. We have 8 places. Currently 23 on the waitlist. Admissions reviews every application and you'll hear back within 3 working days.`,
      meta: [
        ['Background', cap(data.background)],
        ['Experience', cap(data.years)],
        ['Funding choice', data.funding === 'self' ? 'Self-funded · £3,500 up front' : 'Deferred-fee · earn while you learn'],
        ['Email', (data.contact && data.contact.email) || '—'],
        ['Cohort 04 starts', '15 Apr 2027'],
      ],
      next: [
        '20-minute admissions call (within 3 working days).',
        'Half-day practical aptitude assessment at the depot.',
        'Offer / pass on a place within 2 weeks. £100 application fee on accept (refunded on course completion).',
      ],
    }),
  },

  // ---------- ENGINEER: Waitlist (lighter version) ----------
  cohortWaitlist: {
    eyebrow: 'COHORT 05 · TBC',
    title: 'Join the cohort 05 waitlist',
    subtitle: "Cohort 04 (Apr 2027) is filling up. Drop your email and we'll let you know when 05 opens.",
    submitLabel: 'Add me to the waitlist',
    steps: [
      {
        field: 'email',
        component: FlowText,
        props: { label: 'Your email', type: 'email', placeholder: 'you@example.com' },
        validate: (v) => v && /@/.test(v),
      },
      {
        field: 'background',
        component: FlowPills,
        props: {
          label: 'Background (one line, optional)',
          options: [
            { id: 'gas', l: 'Gas Safe' },
            { id: 'plumber', l: 'Plumber' },
            { id: 'electrician', l: 'Electrician' },
            { id: 'mcs', l: 'Already MCS' },
            { id: 'changer', l: 'Career changer' },
          ],
        },
        validate: () => true,
      },
    ],
    onSubmit: (data) => ({
      title: 'On the waitlist.',
      body: `Position 24. We'll email ${data.email} the moment cohort 05 dates are confirmed (likely Q3 2027).`,
      meta: [
        ['Email', data.email],
        ['Cohort 05', 'Q3 2027 (provisional)'],
        ['Position', '24'],
      ],
    }),
  },

  // ---------- BOTH: Generic contact ----------
  contact: {
    eyebrow: 'TALK TO US',
    title: 'Drop us a line',
    subtitle: 'A real human reads it. Reply within four working hours.',
    submitLabel: 'Send message',
    steps: [
      {
        field: 'topic',
        component: FlowPills,
        props: {
          label: 'What do you want to talk about?',
          options: [
            { id: 'partner', l: 'Partner network' },
            { id: 'academy', l: 'Academy / training' },
            { id: 'install', l: 'Heat-pump install' },
            { id: 'press', l: 'Press / media' },
            { id: 'other', l: 'Something else' },
          ],
        },
      },
      {
        field: 'message',
        component: FlowTextarea,
        props: {
          label: 'Your message',
          placeholder: 'A few honest sentences is fine.',
          rows: 5,
        },
        validate: (v) => v && v.trim().length >= 10,
      },
      {
        field: 'contact',
        component: FlowDouble,
        props: {
          label: 'How should we reach you?',
          fields: [
            { id: 'name', placeholder: 'Your name' },
            { id: 'email', type: 'email', placeholder: 'Your email' },
          ],
        },
        validate: (v) => v && v.name && v.email && /@/.test(v.email),
      },
    ],
    onSubmit: (data) => ({
      title: 'Message sent.',
      ref: ref('HL-MSG', 480),
      body: `Thanks${data.contact && data.contact.name ? ', ' + data.contact.name.split(' ')[0] : ''}. We aim to reply within four working hours during weekdays.`,
      meta: [
        ['Topic', cap(data.topic)],
        ['Email', (data.contact && data.contact.email) || '—'],
      ],
    }),
  },

  // ---------- ENGINEER (portal-internal): Open today's pack ----------
  openPack: {
    eyebrow: 'JOB AVL-3091 · ALLESTREE DE22',
    title: "Today's MCS pack",
    subtitle: 'Eight documents bundled and pre-filled. Sign two on site and you\'re done.',
    submitLabel: 'Download as PDF',
    steps: [
      {
        field: 'ack',
        component: FlowPills,
        props: {
          label: 'Pack contents · ready',
          helper: 'You sign the F-Gas log and MCS001/003 on the day. Everything else is pre-filled.',
          options: [
            { id: 'pdf', l: 'PDF bundle (12 MB)' },
            { id: 'split', l: 'Split files (one per doc)' },
            { id: 'wa', l: 'Send to my WhatsApp' },
          ],
        },
      },
    ],
    onSubmit: (data) => ({
      title: 'Pack delivered.',
      body: data.ack === 'wa' ? 'Twelve files have been pushed to your registered WhatsApp number.' : 'Twelve files downloaded to your default folder.',
      meta: [
        ['Heat-loss calc', '✓ ready'],
        ['System design', '✓ ready'],
        ['BUS voucher', '✓ ready'],
        ['Customer welcome pack', '✓ ready'],
        ['Parts kit manifest', '✓ ready'],
        ['Building control notice', '✓ ready'],
        ['F-Gas log entry', '◯ you sign on site'],
        ['MCS001 + MCS003', '◯ you sign on site'],
      ],
    }),
  },

  // ---------- ENGINEER (portal-internal): Message HQ ----------
  messageHQ: {
    eyebrow: 'PARTNER MESSAGE',
    title: 'Message HQ',
    subtitle: 'Sarah K (your account manager) responds in under an hour during work hours.',
    submitLabel: 'Send to Sarah',
    steps: [
      {
        field: 'urgency',
        component: FlowPills,
        props: {
          label: 'How urgent?',
          options: [
            { id: 'now', l: 'On a job · need help now' },
            { id: 'today', l: 'Today' },
            { id: 'this-week', l: 'This week' },
            { id: 'fyi', l: 'Just FYI' },
          ],
        },
      },
      {
        field: 'message',
        component: FlowTextarea,
        props: {
          label: 'What do you need?',
          placeholder: 'Job ref helpful. Photos welcome — paste them later.',
          rows: 5,
        },
        validate: (v) => v && v.trim().length >= 6,
      },
    ],
    onSubmit: (data) => ({
      title: 'Sent to Sarah.',
      body: data.urgency === 'now' ? 'Marked URGENT. Sarah is already in the queue — expect a call within 10 minutes.' : 'Sarah is on it. Expected reply within an hour during work hours.',
      meta: [
        ['Urgency', cap(data.urgency)],
        ['Account manager', 'Sarah K'],
        ['Channel', 'Partner Portal · WhatsApp · email'],
      ],
    }),
  },
};

// ============================================================================
// Click delegation — replace toast with openFlow based on button label
// ============================================================================

const wireFlowClicks = () => {
  document.addEventListener('click', (e) => {
    const btn = e.target.closest('a.btn, button.btn');
    if (!btn) return;
    if (btn.closest('.tab-group')) return;
    if (btn.closest('aside')) return;
    if (btn.tagName === 'A' && btn.getAttribute('href') && btn.getAttribute('href').startsWith('#')) return;

    const label = ((btn.innerText || btn.textContent || '') + '').trim().toLowerCase();
    let flow = null;
    let prefill = {};

    if (/get my fixed quote|get a quote|book a free survey/.test(label)) flow = 'quote';
    else if (/email me/.test(label)) flow = 'emailQuote';
    else if (/whatsapp|call us/.test(label)) flow = 'whatsapp';
    else if (/apply to join the network|apply to join|talk to a partner manager|start application/.test(label)) flow = 'partnerApply';
    else if (/pay up front/.test(label)) { flow = 'partnerApply'; prefill = { funding: 'self' }; }
    else if (/earn while you learn/.test(label)) { flow = 'partnerApply'; prefill = { funding: 'deferred' }; }
    else if (/apply for cohort 04/.test(label)) flow = 'cohortApply';
    else if (/join the waitlist/.test(label)) flow = 'cohortWaitlist';
    else if (/talk to admissions/.test(label)) { flow = 'contact'; prefill = { topic: 'academy' }; }
    else if (/open today/.test(label)) flow = 'openPack';
    else if (/message hq/.test(label)) flow = 'messageHQ';

    if (flow) {
      e.preventDefault();
      e.stopPropagation();
      window.openFlow(flow, prefill);
    }
  }, true);
};

// Run wiring once flows.jsx is loaded.
wireFlowClicks();

// Expose
window.FlowHost = FlowHost;
