/* WLAD Homepage v2 · System diagram + sections 4-7 + modal */

const CAPABILITIES = [
  {
    marker: '01 · The Knowledge Base',
    heading: 'Your brand knowledge lives in the system. Not in 120 slides nobody opens.',
    body: [
      'Four pillars: brand, audience, product, strategy. Built once per brand. Available in every module.',
      "This isn't a style-guide tag. It's the wisdom from which every output is born.",
      'A Q3 newsletter knows what your brand stands for, what your audience needs, what your product is highlighting. Before the first line is written. Updated in realtime across the whole organisation.',
    ],
    outcome: 'The result: brand strategy comes alive in execution.',
  },
  {
    marker: '02 · Output for Judgment',
    heading: 'AI output that empowers your people. Instead of burying them.',
    body: [
      "Generic AI bombards you with text. More output. Faster output. Output without structure, without specification, without provenance. You're supposed to review. But you have no tool to review with.",
      'We build the opposite.',
      'Every output comes with structure, specification, and a complete chain of provenance. You can see exactly what this post came from. From the briefing, to the content plan, to the campaign idea, to the strategy. You can decide, review, approve, or reject. Fully informed, with full context.',
      'Human at the start. Human at the end. AI in the middle, orchestrated on the shared knowledge base. Each in their right place.',
    ],
    outcome: 'The result: AI output your team can actually own.',
  },
  {
    marker: '03 · Strategy Learning',
    heading: 'Most AI tools learn what worked. We learn what your strategy should do next.',
    body: [
      'Generic AI optimizes assets. Headlines, posts, copy. Asset-level. After-the-fact.',
      'We learn one level up. The system measures the strategy itself. Which messaging drives which audience. Which campaign angle compounds across channels. Which positioning decision actually moves the needle.',
      'Every month, that intelligence flows into the next planning cycle. The lowest-performing 20 percent retires. The space gets filled with bold imagination. New angles. New ideas. Risks the system can now afford, because the rest of the strategy earned the room.',
    ],
    outcome: 'The result: a strategy that compounds. With room for boldness.',
  },
];

const S4System = () => {
  const ref = useFade2();
  return (
    <section className="s4 fade2" ref={ref} id="system" data-screen-label="04 System">
      <div className="s4__inner">
        <div className="s4__opener">
          <p className="eyebrow2">The system</p>
          <h2>We call it With Love and Data.</h2>
          <p className="body2 body2--lg" style={{ marginBottom: 18 }}>
            The marketing operating system between strategy and execution.
          </p>
          <p className="body2">
            Across the entire customer journey, from SEO and GEO to social, performance, and CRM.
            Orchestrated, not automated. Human and machine, each in their right place.
          </p>
        </div>

        <div className="s4__diagram">
          <img src="assets/wlad-system.png" alt="The marketing operating system architecture" style={{ width: '100%', height: 'auto', display: 'block' }} />
          <div className="s4__diagram-cap">Four pillars · five disciplines · one feedback loop</div>
        </div>

        <div className="s4__caps">
          {CAPABILITIES.map((c, i) => (
            <div key={i} className="s4__cap">
              <div className="s4__cap-marker">{c.marker}</div>
              <h3 className="s4__cap-h">{c.heading}</h3>
              <div className="s4__cap-body">
                {c.body.map((p, k) => <p key={k} className="body2">{p}</p>)}
              </div>
              <p className="s4__cap-outcome s4__cap-outcome--bare">
                <span className="wlad-magician--gradient">{c.outcome}</span>
              </p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ---------- S5 Proof · three customer cards, no magic ---------- */
const S5Proof = ({ onTalk }) => {
  const ref = useFade2();
  const cases = [
    {
      marker: '01 · Teroson / Henkel',
      h: 'Four countries, aligned. Without losing what made each one strong.',
      body: [
        'Teroson runs marketing across Germany, Italy, England, and France. Each country team had high creative freedom. And growing strategic misalignment.',
        'We deployed the system through their agency. A central, structured plan. One core strategy. Country teams in full alignment, creative strengths intact.',
        'After a year of watching the results from outside, Henkel asked for the system internally, for other brands. Pull, not push.',
      ],
      outcomes: [
        ['Alignment', '4 countries'],
        ['Consistency', 'One strategic core'],
        ['Rollout', 'Internal pull, agency-led'],
      ],
    },
    {
      marker: '02 · TÜV Rheinland',
      h: 'From eight hours to fifteen minutes. At higher quality.',
      body: [
        'TÜV Rheinland turns dense technical whitepapers into engaging social content, blog posts, and newsletters. Manual process. Subject-matter-expert-dependent. Eight hours per piece.',
        'The system reduced that to fifteen minutes. While raising quality, accuracy, and brand safety.',
      ],
      quote: '"The quality of the results is fantastic."',
      attr: 'TÜV Rheinland team',
      outcomes: [
        ['Time', '8h → 15min per piece'],
        ['Quality', 'Higher than manual'],
        ['Brand safety', 'Higher than manual'],
      ],
    },
    {
      marker: '03 · Stealth Customer',
      h: 'Three brands. One platform. One coordinated rollout.',
      body: [
        'They came in at 48 comment loops per asset. 15+ people per newsletter. Brand compliance at three or four out of ten.',
        'Stage-1 pilot, three months. Targets: 3-5 comment loops, 7-8/10 compliance, 80% on-strategy. Multi-brand architecture across three brands under one parent.',
      ],
      outcomes: [
        ['Comment loops', '48 → 3–5'],
        ['Compliance', '3–4/10 → 7–8/10'],
        ['Brands', 'Three under one parent'],
      ],
    },
  ];
  return (
    <section className="s5 fade2" ref={ref} id="proof" data-screen-label="05 Proof">
      <div className="s5__inner">
        <div className="s5__head">
          <p className="eyebrow2">Proof</p>
          <h2>From production.</h2>
        </div>
        <div className="s5__cards">
          {cases.map((c) => (
            <article className="s5__card" key={c.marker}>
              <div className="s5__card-grid">
                <div>
                  <div className="s5__marker">{c.marker}</div>
                  <h3 className="s5__h">{c.h}</h3>
                  <div className="s5__body">
                    {c.body.map((p, i) => <p key={i}>{p}</p>)}
                    {c.quote && (
                      <>
                        <blockquote className="s5__quote">{c.quote}</blockquote>
                        <div className="s5__attr">{c.attr}</div>
                      </>
                    )}
                  </div>
                  <button type="button" className="s5__more" onClick={() => onTalk()}>Learn more <Arrow2 /></button>
                </div>
                <div className="s5__outcomes">
                  {c.outcomes.map(([l, v]) => (
                    <div className="s5__outcome" key={l}>
                      <div className="s5__outcome-label">{l}</div>
                      <div className="s5__outcome-val">{v}</div>
                    </div>
                  ))}
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ---------- S6 Belief ---------- */
const S6Belief = () => {
  const ref = useFade2();
  return (
    <section className="s6 fade2" ref={ref} id="belief" data-screen-label="06 Belief">
      <div className="s6__inner">
        <p className="eyebrow2 eyebrow2--cream">The belief</p>
        <blockquote className="s6__pull">
          Structure, done right, doesn't constrain creativity. <em>It worships it.</em>
        </blockquote>
      </div>
    </section>
  );
};

/* ---------- S7 CTA ---------- */
const S7CTA = ({ onTalk }) => {
  const ref = useFade2();
  const cards = [
    { m: '01 · Strategy', h: 'A 30-minute strategy conversation.', b: "For CMOs and VPs. No demo pressure. We talk about your in-housing risk, the gap between your strategy and execution, and whether the operating system gives you back the control you lost when agencies were cut.", persona: 'Strategy' },
    { m: '02 · Brand', h: 'A 60-minute walkthrough.', b: "For brand leads. See what it looks like when your strategy actually survives execution. On-brand at every touchpoint, at scale, without the dilution and the AI-slop.", persona: 'Brand' },
    { m: '03 · Execution', h: 'A 45-minute live walkthrough.', b: "For marketing managers. See a whole month of planning, briefing, and analytics, done in a single morning. On-strategy. From your brand DNA.", persona: 'Execution' },
  ];
  return (
    <section className="s7 fade2" ref={ref} id="cta" data-screen-label="07 CTA">
      <div className="s7__inner">
        <div className="s7__head">
          <p className="eyebrow2">Next step</p>
          <h2>The next step is small.</h2>
          <p className="body2 body2--lg">
            Tell us what's breaking. We'll tell you exactly how we'd fix it. If it fits, we plan a
            pilot. If not, you'll have 30 minutes of clarity about what you actually need. And
            that's worth something too.
          </p>
        </div>
        <div className="s7__cards">
          {cards.map((c) => (
            <div className="s7__card" key={c.m}>
              <div className="s7__card-marker">{c.m}</div>
              <h3 className="s7__card-h">{c.h}</h3>
              <p className="s7__card-body">{c.b}</p>
              <a className="s7__card-cta" href="https://calendar.notion.so/meet/ajacobi/40n1e4p2x" target="_blank" rel="noopener noreferrer">Book a slot <Arrow2 /></a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ---------- Footer ---------- */
const Footer2 = () => (
  <footer className="f2" id="footer-v2" data-screen-label="08 Footer">
    <div className="f2__inner">
      <a className="f2__logo" href="#top">
        <img src="assets/logo-light.png" alt="With Love and Data" />
      </a>
      <nav className="f2__links">
        <a href="#proof">Case studies</a>
        <a href="#about">About</a>
        <a href="#cta">Contact</a>
      </nav>
      <div className="f2__legal">© 2026 · <a href="https://wladnext.notion.site/With-love-and-data-350ad1cba176816fb21df9f2d4d5580c" target="_blank" rel="noopener noreferrer">Imprint</a> · <a href="https://wladnext.notion.site/With-love-and-data-350ad1cba17681c9a4a5f20f38466beb" target="_blank" rel="noopener noreferrer">Privacy</a> · Terms</div>
    </div>
  </footer>
);

/* ---------- Talk modal ---------- */
const WEB3FORMS_KEY = '4aa8558d-2af8-42be-a633-7db7643f290f';

const TalkModal = ({ open, onClose, persona }) => {
  const [step, setStep] = React.useState('form');
  const [form, setForm] = React.useState({ name: '', email: '', company: '', role: '', persona: 'Strategy', context: '', botcheck: '' });
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setStep('form'); setErrors({});
      if (persona) setForm((f) => ({ ...f, persona }));
    }
  }, [open, persona]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape' && open) onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    const errs = {};
    if (!form.name.trim()) errs.name = true;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errs.email = true;
    if (!form.company.trim()) errs.company = true;
    setErrors(errs);
    if (Object.keys(errs).length) return;

    setSubmitting(true);
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          access_key: WEB3FORMS_KEY,
          subject: `New talk request — ${form.name} (${form.company})`,
          from_name: 'With Love and Data — Site',
          replyto: form.email,
          name: form.name,
          email: form.email,
          company: form.company,
          role: form.role,
          conversation: form.persona,
          context: form.context,
          botcheck: form.botcheck,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setStep('done');
      } else {
        setErrors({ submit: data.message || 'Could not send. Please email us directly: alex@withloveanddata.com' });
      }
    } catch (err) {
      setErrors({ submit: 'Network error. Please email us directly: alex@withloveanddata.com' });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className={`m2-scrim ${open ? 'open' : ''}`} onClick={onClose} role="dialog" aria-modal="true" aria-hidden={!open}>
      <div className="m2" onClick={(e) => e.stopPropagation()}>
        <button className="m2__close" onClick={onClose} aria-label="Close">×</button>
        {step === 'form' ? (
          <>
            <p className="m2__eyebrow">Let's talk · 24h response</p>
            <h3 className="m2__title">Tell us where you'd start.</h3>
            <p className="m2__body">
              We listen. We understand. We think. Then we tell you what we'd actually do. If it
              fits, we plan a pilot. If not, you walk away with 30 minutes of clarity about what
              you need.
            </p>
            <form onSubmit={submit}>
              <div className="m2__row">
                <div className="m2__field">
                  <label className="m2__label">Your name</label>
                  <input className={`m2__input ${errors.name ? 'error' : ''}`} value={form.name} onChange={(e) => set('name', e.target.value)} placeholder="Alex Jacobi" />
                </div>
                <div className="m2__field">
                  <label className="m2__label">Work email</label>
                  <input className={`m2__input ${errors.email ? 'error' : ''}`} value={form.email} onChange={(e) => set('email', e.target.value)} placeholder="alex@company.com" />
                </div>
              </div>
              <div className="m2__row">
                <div className="m2__field">
                  <label className="m2__label">Company</label>
                  <input className={`m2__input ${errors.company ? 'error' : ''}`} value={form.company} onChange={(e) => set('company', e.target.value)} placeholder="Acme Brands" />
                </div>
                <div className="m2__field">
                  <label className="m2__label">Role</label>
                  <input className="m2__input" value={form.role} onChange={(e) => set('role', e.target.value)} placeholder="Head of Brand" />
                </div>
              </div>
              <div className="m2__field">
                <label className="m2__label">Which conversation?</label>
                <select className="m2__select" value={form.persona} onChange={(e) => set('persona', e.target.value)}>
                  <option>Strategy · 30 min, for CMOs / VPs</option>
                  <option>Brand · 60 min, for brand leads</option>
                  <option>Execution · 45 min, for marketing managers</option>
                </select>
              </div>
              <div className="m2__field">
                <label className="m2__label">What's breaking?</label>
                <textarea className="m2__textarea" value={form.context} onChange={(e) => set('context', e.target.value)} placeholder="One brand, three brands, multiple markets, current stack, where the chain is breaking..." />
              </div>
              <input type="text" name="botcheck" tabIndex={-1} autoComplete="off" aria-hidden="true" value={form.botcheck} onChange={(e) => set('botcheck', e.target.value)} style={{ position: 'absolute', left: '-9999px', width: 1, height: 1 }} />
              {errors.submit && <p className="m2__error" role="alert">{errors.submit}</p>}
              <div className="m2__footer">
                <span className="m2__hint">Reply within 24h, with two slot options.</span>
                <button type="submit" className="btn2 btn2--magenta" disabled={submitting}>{submitting ? 'Sending…' : 'Send'} <Arrow2 /></button>
              </div>
            </form>
          </>
        ) : (
          <div className="m2__success">
            <div className="m2__success-icon">✓</div>
            <h3 className="m2__title" style={{ textAlign: 'center' }}>Got it. We'll be in touch.</h3>
            <p className="m2__body" style={{ textAlign: 'center' }}>
              A note is on its way to <strong>{form.email}</strong>. We'll respond within 24 hours
              with two slot options.
            </p>
            <div style={{ display: 'flex', justifyContent: 'center', marginTop: 8 }}>
              <button className="btn2 btn2--ink" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { S4System, S5Proof, S6Belief, S7CTA, Footer2, TalkModal });
