// Discovery page app shell — hero, form wizard, review, thank-you.
const { useState, useEffect, useMemo, useCallback } = React;

const STEP_SHORT = ['Business', 'Goals', 'Systems', 'Data', 'Future'];
const SCHEMA = window.SCHEMA;
SCHEMA.steps.forEach((s, i) => s.shortLabel = STEP_SHORT[i]);

function App() {
  const [tweaks, setTweaksState] = useState(() => ({
    ...(window.TWEAK_DEFAULTS || {}),
  }));
  const [tweaksOpen, setTweaksOpen] = useState(false);

  useEffect(() => {
    const handler = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const setTweaks = (partial) => {
    setTweaksState(prev => {
      const next = { ...prev, ...partial };
      try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: partial }, '*'); } catch (e) {}
      return next;
    });
  };

  // route state: 'landing' | 'form' | 'thanks'
  const [route, setRoute] = useState('landing');
  const [stepIdx, setStepIdx] = useState(0); // 0..4 or 5 for review
  const [values, setValues] = useState({});
  const [errors, setErrors] = useState({});

  const setValue = (id, v) => {
    setValues(prev => ({ ...prev, [id]: v }));
    setErrors(prev => {
      if (!prev[id]) return prev;
      const n = { ...prev }; delete n[id]; return n;
    });
  };

  const activeDeepDives = useMemo(() =>
    SCHEMA.deepDives.filter(dd => dd.match(values.areas)), [values.areas]);

  // Visible fields of current step, honoring per-field conditional predicates
  const currentStep = SCHEMA.steps[stepIdx];
  const visibleFields = (currentStep ? currentStep.fields : []).filter(f => {
    if (!f.conditional) return true;
    try { return f.conditional(values); } catch (e) { return true; }
  });

  function validateStep() {
    const e = {};
    for (const f of visibleFields) {
      if (!f.required) continue;
      const v = values[f.id];
      if (f.type === 'multi') {
        if (!v || v.length === 0) e[f.id] = 'Please choose at least one option.';
      } else if (f.type === 'segmented' || f.type === 'select') {
        if (!v) e[f.id] = 'Please choose an option.';
      } else {
        if (!v || !String(v).trim()) e[f.id] = 'This field is required.';
      }
      if (f.type === 'email' && v && !/^\S+@\S+\.\S+$/.test(v)) e[f.id] = 'Enter a valid email.';
    }
    setErrors(e);
    if (Object.keys(e).length > 0) {
      // scroll to first error
      setTimeout(() => {
        const first = document.querySelector('.field.has-error');
        if (first) first.scrollIntoView ? first.scrollIntoView({ behavior: 'smooth', block: 'center' }) : null;
      }, 30);
      return false;
    }
    return true;
  }

  function goNext() {
    if (!validateStep()) return;
    if (stepIdx < SCHEMA.steps.length - 1) {
      setStepIdx(stepIdx + 1);
      window.scrollTo({ top: document.querySelector('.form-shell').offsetTop - 20, behavior: 'smooth' });
    } else {
      // go to review
      setStepIdx(SCHEMA.steps.length); // review
      window.scrollTo({ top: document.querySelector('.form-shell').offsetTop - 20, behavior: 'smooth' });
    }
  }
  function goBack() {
    if (stepIdx === 0) { setRoute('landing'); return; }
    setStepIdx(stepIdx - 1);
  }

  return (
    <>
      <TopNav />
      <div className="page">
        {route === 'landing' && <Landing tweaks={tweaks} onStart={() => { setRoute('form'); setStepIdx(0); setTimeout(() => window.scrollTo({ top: document.querySelector('.form-shell').offsetTop - 20, behavior: 'smooth' }), 50); }} />}
        {route === 'form' && stepIdx < SCHEMA.steps.length && (
          <Landing tweaks={tweaks} onStart={() => {}} hideCta>
            <FormWizard
              tweaks={tweaks} stepIdx={stepIdx} step={currentStep} visibleFields={visibleFields}
              values={values} errors={errors} setValue={setValue}
              activeDeepDives={activeDeepDives}
              onBack={goBack} onNext={goNext}
              onJumpTo={i => setStepIdx(i)}
            />
          </Landing>
        )}
        {route === 'form' && stepIdx === SCHEMA.steps.length && (
          <Landing tweaks={tweaks} onStart={() => {}} hideCta>
            <ReviewScreen values={values} activeDeepDives={activeDeepDives}
                          onEdit={i => setStepIdx(i)}
                          onBack={() => setStepIdx(SCHEMA.steps.length - 1)}
                          onSubmit={async () => {
                            try {
                              if (window.HUBSPOT_CONFIG && window.HUBSPOT_CONFIG.formGuid) {
                                await window.submitToHubSpot(values);
                              } else {
                                console.warn('HubSpot not configured — skipping real submission. Run setup-hubspot.js.');
                              }
                              setRoute('thanks');
                            } catch (err) {
                              alert('Submission failed: ' + err.message + '\n\nYour answers are still here — please try again.');
                            }
                          }} />
          </Landing>
        )}
        {route === 'thanks' && <ThankYou onReset={() => { setRoute('landing'); setStepIdx(0); setValues({}); setErrors({}); }} />}
      </div>
      <Footer />
      <TweaksPanel state={tweaks} setState={setTweaks} open={tweaksOpen} />
      <div style={{ position: 'fixed', top: 0, left: 0, width: 0, height: 0 }} data-accent={tweaks.accent === 'amber' ? 'amber' : null} />
    </>
  );
}

// Apply accent attribute to <html>
function useAccent(tweaks) {
  useEffect(() => {
    if (tweaks.accent === 'amber') document.documentElement.setAttribute('data-accent', 'amber');
    else document.documentElement.removeAttribute('data-accent');
  }, [tweaks.accent]);
}

// ─── Nav ─────────────────────────────────────────────────────────
function TopNav() {
  return (
    <nav className="nav">
      <a className="nav-brand" href="#">
        <img src="assets/logo-white.png" alt="NVC360" />
        <div>
          <div className="nav-brand-text">NVC360<small>AI Automation</small></div>
        </div>
      </a>
      <div className="nav-aux"><strong>Discovery</strong> · ~8 minutes</div>
    </nav>
  );
}
function Footer() {
  return (
    <footer className="footer">
      © 2026 NVC360 AI Automation · Winnipeg, MB · <a href="#">Privacy</a> · <a href="#">Contact</a>
    </footer>
  );
}

// ─── Landing (hero + benefits + form slot) ───────────────────────
function Landing({ tweaks, onStart, hideCta, children }) {
  useAccent(tweaks);
  return (
    <>
      <Hero tweaks={tweaks} onStart={onStart} hideCta={hideCta} />
      {tweaks.showBenefitStrip !== false && <BenefitStrip />}
      <div className="container">
        {children}
      </div>
    </>
  );
}

function Hero({ tweaks, onStart, hideCta }) {
  return (
    <section className="hero">
      <div className="container">
        <div className="eyebrow"><span className="dot" />AI Automation — Discovery Intake</div>
        <h1>Tell us where <span className="accent">AI can create the most value</span> in your business</h1>
        <p className="subhead">
          Use this discovery form to help us understand your workflows, existing systems, data sources, pain points, and desired future state. We'll use your responses to prepare the smartest first step for your AI automation initiative.
        </p>
        <p className="support">
          No prep is required. If you're unsure about a question, choose "Not sure" or leave any optional field blank. We only ask for the information we need to begin discovery.
        </p>
        {!hideCta && (
          <div className="hero-cta-row">
            <button className="btn btn-primary" onClick={onStart}>
              Start discovery <span className="arrow-r"><IconArrow size={14} /></span>
            </button>
            <span style={{ fontSize: 13, color: 'var(--text-muted)', marginLeft: 4 }}>No credit card · Takes ~8 minutes</span>
          </div>
        )}

        {tweaks.heroVariant === 'stats' && <HeroStats />}
        {tweaks.heroVariant === 'kpi' && <HeroKpi />}
      </div>
    </section>
  );
}

function HeroStats() {
  return (
    <div className="hero-stats">
      <div className="hero-stat"><div className="num">5 steps</div><div className="lbl">Focused, single-column form — no CRM, no resume needed.</div></div>
      <div className="hero-stat"><div className="num">~8 min</div><div className="lbl">Short paragraphs and choose-from-list questions. Skip anything you're unsure of.</div></div>
      <div className="hero-stat"><div className="num">1st phase</div><div className="lbl">We respond with a scoped first use case within 2 business days.</div></div>
    </div>
  );
}

function HeroKpi() {
  return (
    <div className="kpi-strip">
      <div className="kpi"><b>5 steps</b><span>Single-column form</span></div>
      <div className="kpi"><b>~8 min</b><span>To complete</span></div>
      <div className="kpi"><b>2 business days</b><span>Follow-up</span></div>
      <div className="kpi"><b>100% confidential</b><span>NDA available on request</span></div>
    </div>
  );
}

function BenefitStrip() {
  const items = [
    { t: 'Practical, business-first discovery', p: 'Questions framed around outcomes and workflows — not AI theory.' },
    { t: 'Focused on your current systems and workflows', p: 'We design around what you already run, not what you\'d have to rebuild.' },
    { t: 'Designed to identify the highest-value first phase', p: 'You leave with a clear, scoped starting point — not a generic roadmap.' }
  ];
  return (
    <section className="benefits">
      <div className="container-wide">
        <div className="benefits-grid">
          {items.map(it => (
            <div key={it.t} className="benefit">
              <span className="mark"><IconCheck size={16} /></span>
              <h3>{it.t}</h3>
              <p>{it.p}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Form wizard ─────────────────────────────────────────────────
function FormWizard({ tweaks, stepIdx, step, visibleFields, values, errors, setValue,
                     activeDeepDives, onBack, onNext, onJumpTo }) {
  return (
    <div className="form-shell step" key={`step-${stepIdx}`}>
      <Progress steps={SCHEMA.steps} current={stepIdx} onNavigate={onJumpTo} />
      <div className="form-body">
        <div className="step-header">
          <div className="step-kicker">{step.kicker}</div>
          <h2 className="step-title">{step.title}</h2>
          <p className="step-intro">{step.intro}</p>
        </div>

        {visibleFields.map(f => (
          <Field key={f.id} def={f} value={values[f.id]} error={errors[f.id]}
                 onChange={v => setValue(f.id, v)} />
        ))}

        {/* Deep-dives appear at the end of step 2 (Goals) */}
        {stepIdx === SCHEMA.deepDiveStep && activeDeepDives.length > 0 && (
          <div style={{ marginTop: 28 }}>
            {activeDeepDives.map(dd => (
              <DeepDive key={dd.id} dd={dd} values={values}
                        display={tweaks.conditionalDisplay || 'inline'}
                        onChange={setValue} errors={errors} />
            ))}
          </div>
        )}

        <div className="form-nav">
          <button className="btn btn-ghost" onClick={onBack}>
            <IconArrow dir="left" size={14} /> Back
          </button>
          <div className="right">
            <span className="step-meta" style={{ alignSelf: 'center', marginRight: 8 }}>
              Step {stepIdx + 1} of {SCHEMA.steps.length}
            </span>
            <button className="btn btn-primary" onClick={onNext}>
              {stepIdx === SCHEMA.steps.length - 1 ? 'Review your answers' : 'Continue'}
              <span className="arrow-r"><IconArrow size={14} /></span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Review screen ───────────────────────────────────────────────
function ReviewScreen({ values, activeDeepDives, onEdit, onBack, onSubmit }) {
  const fmt = (v) => {
    if (v === undefined || v === null || v === '') return <span className="empty">Not answered</span>;
    if (Array.isArray(v)) {
      if (v.length === 0) return <span className="empty">Not answered</span>;
      return <ul>{v.map(x => <li key={x}>{x}</li>)}</ul>;
    }
    return String(v);
  };

  return (
    <div className="form-shell step">
      <div className="form-progress">
        <div className="progress-labels">
          {SCHEMA.steps.map((s, i) => (
            <button key={s.id} type="button" className="progress-label is-done"
                    onClick={() => onEdit(i)}
                    style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
              <span className="n"><IconCheck size={10} /></span>
              <span className="t">{s.shortLabel}</span>
            </button>
          ))}
        </div>
        <div className="progress-bar"><div className="progress-fill" style={{ width: '100%' }} /></div>
      </div>

      <div className="form-body">
        <div className="step-header">
          <div className="step-kicker">Review</div>
          <h2 className="step-title">One last look before you send it over</h2>
          <p className="step-intro">
            Have a quick read. You can jump back to any step to edit — nothing is submitted until you confirm.
          </p>
        </div>

        {SCHEMA.steps.map((s, i) => (
          <div key={s.id} className="review-section">
            <h3>
              <span>{s.title}</span>
              <button className="edit" onClick={() => onEdit(i)}>Edit</button>
            </h3>
            <div className="kicker">Step {i + 1}</div>
            {s.fields.filter(f => !f.conditional || (()=>{ try { return f.conditional(values); } catch(e){ return true; } })()).map(f => (
              <div key={f.id} className="review-item">
                <div className="k">{f.label}</div>
                <div className="v">{fmt(values[f.id])}</div>
              </div>
            ))}
          </div>
        ))}

        {activeDeepDives.map(dd => (
          <div key={dd.id} className="review-section">
            <h3>
              <span>{dd.label}</span>
              <button className="edit" onClick={() => onEdit(SCHEMA.deepDiveStep)}>Edit</button>
            </h3>
            <div className="kicker">Conditional deep-dive</div>
            {dd.fields.map(f => (
              <div key={f.id} className="review-item">
                <div className="k">{f.label}</div>
                <div className="v">{fmt(values[f.id])}</div>
              </div>
            ))}
          </div>
        ))}

        <div className="form-nav">
          <button className="btn btn-ghost" onClick={onBack}>
            <IconArrow dir="left" size={14} /> Back to step 5
          </button>
          <button className="btn btn-primary" onClick={onSubmit}>
            Submit discovery <span className="arrow-r"><IconArrow size={14} /></span>
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Thank-you state ─────────────────────────────────────────────
function ThankYou({ onReset }) {
  return (
    <section className="hero" style={{ paddingTop: 32 }}>
      <div className="container">
        <div className="form-shell">
          <div className="thankyou">
            <div className="checkmark"><IconBig size={34} /></div>
            <h2>Thanks — we have what we need to begin the initial discovery process.</h2>
            <p>
              We'll review your responses to identify the highest-value first use case, the key systems and workflow dependencies, and the right next-step conversation for your team. Expect a response within 2 business days.
            </p>
            <div className="cta-row">
              <a className="btn btn-primary" href="#">
                Book a discovery call <span className="arrow-r"><IconArrow size={14} /></span>
              </a>
              <button className="btn btn-secondary" onClick={onReset}>Start a new submission</button>
            </div>
            <div className="meta">
              A confirmation has been sent to your work email. Have a file to share? Reply to that email with attachments and we'll link it to your intake.
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

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