/* Section views. Each rendered inside SectionView shell. */
const { useState: useStateSec, useEffect: useEffectSec } = React;

/* Animated portrait — auto-crossfading reel of photos, looping like a gif. */
function PortraitReel({ shots }) {
  const [i, setI] = useStateSec(0);
  useEffectSec(() => {
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce || shots.length < 2) return;
    const id = setInterval(() => setI((n) => (n + 1) % shots.length), 2600);
    return () => clearInterval(id);
  }, [shots.length]);
  return (
    <div className="reel">
      {shots.map((s, n) =>
      <img
        key={n}
        className={'reel-img' + (n === i ? ' on' : '')}
        src={s.src}
        alt="Manassanun Oom Noksakul"
        loading={n === 0 ? 'eager' : 'lazy'} />
      )}
      <div className="reel-cap" aria-live="off">{shots[i].cap}</div>
      <div className="reel-dots">
        {shots.map((s, n) =>
        <button
          key={n}
          className={'reel-dot' + (n === i ? ' on' : '')}
          aria-label={'Show photo ' + (n + 1)}
          onClick={() => setI(n)}></button>
        )}
      </div>
    </div>);

}

function SectionView({ tag, num, title, intro, onBack, children }) {
  return (
    <div className="section-view">
      <div className="shell">
        <div className="sv-head">
          <div className="sv-titlewrap">
            <div className="sv-num">{num}</div>
            <div>
              <h1 className="sv-title" dangerouslySetInnerHTML={{ __html: title }} />
              {intro && <p className="sv-intro">{intro}</p>}
            </div>
          </div>
        </div>
        {children}
      </div>
    </div>);

}

/* 1 — How */
function HowSection({ onBack }) {
  return (
    <SectionView tag="How to collaborate" num="" onBack={onBack}
    title="How we work, <em>move&nbsp;by&nbsp;move</em>."
    intro="A recipe I borrowed from strategy work and bent toward design, the 5+ approaches based on business context and its lifecycle.">
      <div className="approach-grid reveal">
        {DATA.approaches.map((ap) =>
        <div className={'approach' + (ap.placeholder ? ' placeholder' : '')} key={ap.n}>
            <div className="top"><span className="n">{ap.n}</span><span className="phase">{ap.phase}</span></div>
            <h3 style={{ color: "var(--accent)" }}>{ap.name}</h3>
            <p>{ap.blurb}</p>
            <button className="see-how" type="button" disabled aria-disabled="true" title="Coming soon">See how →</button>
          </div>
        )}
      </div>
    </SectionView>);

}

/* 2 — Which */
function WhichSection({ onBack }) {
  return (
    <SectionView tag="Which artefacts to use" num="" onBack={onBack}
    title="The artefacts I <em>reach&nbsp;for</em>."
    intro="Tools for thinking, not decks for show. Each one earns its place by changing what a room can see. A few of my regulars.">
      <div className="artefact-grid reveal">
        {DATA.artefacts.map((art) =>
        <div className="artefact" key={art.key}>
            <div className="sample"><ArtefactSample kind={art.key} /></div>
            <div className="body">
              <span className="tag"></span>
              <div className="nm" style={{ color: "var(--accent)" }}>{art.name}</div>
              <p>{art.blurb}</p>
            </div>
          </div>
        )}
      </div>
    </SectionView>);

}

/* 3 — Who */
function WhoSection({ onBack }) {
  const w = DATA.who;
  return (
    <SectionView tag="Who I am" num="" onBack={onBack}
    title="Who I am, <em>roughly</em>.">
      <div className="who-wrap">
        <div>
          <p className="who-lead reveal">{w.lead} I design how it <em>works</em>, how it <em>feels</em>, and how teams work for it.</p>
          <div className="prose">
            {w.body.map((para, i) => <p className="reveal" key={i} dangerouslySetInnerHTML={{ __html: para }}></p>)}
          </div>
          <div className="facts reveal">
            {w.facts.map((f, i) =>
            <div className="f" key={i}><div className="k">{f.k}</div><div className="v">{f.v}</div></div>
            )}
          </div>
        </div>
        <div className="who-portrait reveal">
          <div className="frame">
            <PortraitReel shots={w.portraits} />
          </div>
          <div className="cap">Oom in her natural habitats</div>
        </div>
      </div>
    </SectionView>);

}

/* Why — line-work illustration: a bloom above the surface (the visible work,
   in accent) growing from a deep, branching root system (the real problems).
   Ink on Paper, single weight — per the Oom illustration spec. */
function WhyIllustration() {
  return (
    <svg className="why-art" viewBox="0 0 260 408" role="img"
    aria-label="A small bloom above the ground, growing from a deep branching root system below."
    fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      {/* ground — a dotted soil line dividing the seen from the unseen */}
      <path d="M18,170 H242" strokeWidth="1.6" strokeDasharray="0.5 7" opacity="0.4" />

      {/* above the surface — stem, leaves, bloom (the visible five percent) */}
      <path d="M130,170 C131,148 130,126 130,106" />
      <path d="M130,120 C120,113 109,116 106,123 C110,130 121,130 130,120 Z" />
      <path d="M127,122 L110,123" opacity="0.55" />
      <path d="M130,134 C141,127 152,130 155,137 C151,144 140,144 130,134 Z" />
      <path d="M133,136 L150,137" opacity="0.55" />
      <path d="M130,106 C130,99 130,95 130,91" />
      <circle cx="130" cy="82" r="7.5" stroke="var(--accent)" />
      <circle cx="130" cy="82" r="2" fill="var(--accent)" stroke="none" />
      <path stroke="var(--accent)" d="M130,74 L130,62 M130,76 L121,67 M130,76 L139,67" />

      {/* below the surface — the root system (where the real problems sit) */}
      <g opacity="0.9">
        <path d="M130,170 C129,202 125,232 127,264 C129,290 123,316 120,342 C118,358 117,372 116,388" />
        <path d="M126,248 C117,256 110,266 106,278" />
        <path d="M128,298 C137,308 141,318 144,330" />

        <path d="M128,172 C112,196 91,212 79,242 C69,266 63,288 57,316 C54,330 52,342 50,356" />
        <path d="M85,234 C75,238 69,246 65,256" />
        <path d="M69,286 C61,292 57,300 54,310" />

        <path d="M132,172 C150,194 172,208 186,238 C197,262 203,286 208,314 C211,328 213,340 215,354" />
        <path d="M180,230 C190,234 196,242 200,252" />
        <path d="M198,286 C206,292 210,300 213,310" />
      </g>

      {/* nodes where the system branches, and the deepest root — the root cause */}
      <circle cx="126" cy="248" r="1.7" fill="currentColor" stroke="none" opacity="0.45" />
      <circle cx="85" cy="234" r="1.7" fill="currentColor" stroke="none" opacity="0.45" />
      <circle cx="180" cy="230" r="1.7" fill="currentColor" stroke="none" opacity="0.45" />
      <circle cx="116" cy="388" r="2.6" fill="var(--accent)" stroke="none" />
    </svg>);

}

/* 4 — Why */
function WhySection({ onBack }) {
  const w = DATA.why;
  return (
    <SectionView tag="Why I design" num="" onBack={onBack}
    title="Why I <em>design</em>.">
      <h2 className="why-statement reveal">Creativity can solve problems and <em>raise the quality of a life</em>.</h2>
      <div className="why-body">
        <figure className="why-figure reveal">
          <WhyIllustration />
          <figcaption className="cap">the work is at the root</figcaption>
        </figure>
        <div className="prose">
          {w.body.map((para, i) => <p className="reveal" key={i}>{para}</p>)}
        </div>
      </div>
      <div className="pillars reveal">
        {w.pillars.map((p, i) =>
        <div className="pillar" key={i}><div className="k">{p.k}</div><div className="v">{p.v}</div></div>
        )}
      </div>
    </SectionView>);

}

/* 5 — What */
function WhatSection({ onBack, layout = 'gallery' }) {
  const ps = DATA.projects;
  return (
    <SectionView tag="What is my work" num="" onBack={onBack}
    title="What I've <em>made</em>."
    intro="Overview of the impact driven by designs. Please reach out for the full case study details.">
      <div className="work-toolbar">
        <span className="count">More cases to show…</span>
        <span className="count">…just not here</span>
      </div>
      <div className={'work ' + layout}>
        {ps.map((p) => layout === 'index' ?
        <div className="pcard" key={p.id}>
            <span className="pidx-inline">{String(p.id).padStart(2, '0')}</span>
            <h3>{p.title}</h3>
            <span className="ic">{p.company}</span>
            <span className="ic">{p.year}</span>
            <span className="impact">{p.impact}</span>
          </div> :

        <div className="pcard" key={p.id}>
            <div className="cover">
              <image-slot id={'project-cover-' + p.id} src={'assets/covers/project-' + p.id + '.webp'} shape="rect" fit="cover" placeholder="Drop a cover image"></image-slot>
              <span className="pidx">{String(p.id).padStart(2, '0')}</span>
            </div>
            <div className="pbody">
              <div className="pmeta"><span>{p.company}</span><span>{p.year}</span></div>
              <h3>{p.title}</h3>
              <div className="skills">{p.skills.map((s, i) => <span key={i}>{s}</span>)}</div>
              <div className="impact">{p.impact}</div>
              <button className="case-btn" type="button" disabled aria-disabled="true" title="Case study coming soon">View case study →</button>
            </div>
          </div>
        )}
      </div>
    </SectionView>);

}

/* 6 — Where */
function WhereSection({ onBack }) {
  const host = (url) => url.replace(/^https?:\/\//, '').replace(/^www\./, '').replace(/\/.*$/, '');
  const links = DATA.inspiration.flatMap((g) => g.links);
  return (
    <SectionView tag="Where I get inspired" num="" onBack={onBack}
    title="Where I get <em>inspired</em>."
    intro="A working library — the people, tools and ideas I keep returning to. Open any door; they all lead somewhere good.">
      <div className="insp-cards reveal">
        {links.map((l, i) =>
        <a className="insp-card" key={i} href={l.url} target="_blank" rel="noopener noreferrer">
            <span className="nm">{l.name}</span>
            <span className="host">{host(l.url)} ↗</span>
          </a>
        )}
      </div>
    </SectionView>);

}

/* 7 — When */
function WhenSection({ onBack }) {
  const [sent, setSent] = useStateSec(false);
  const [sending, setSending] = useStateSec(false);
  const [err, setErr] = useStateSec(false);
  const [copied, setCopied] = useStateSec(false);
  const [kinds, setKinds] = useStateSec([]);
  const email = DATA.person.email;
  const projectTypes = ['Feedback', 'Collaboration', 'Design Discussion', 'Mindfulness', 'Horse', 'Just curious'];
  const toggle = (k) => setKinds((ks) => ks.includes(k) ? ks.filter((x) => x !== k) : [...ks, k]);
  const copyEmail = () => {
    navigator.clipboard?.writeText(email).then(() => {setCopied(true);setTimeout(() => setCopied(false), 1800);}).catch(() => {});
  };
  const submitForm = (e) => {
    e.preventDefault();
    if (sending) return;
    const form = e.currentTarget;
    const data = new FormData(form);
    data.append('Topics', kinds.length ? kinds.join(', ') : '—');
    data.append('_subject', 'Curiouser — a new note from ' + (data.get('name') || 'someone'));
    data.append('_template', 'table');
    data.append('_captcha', 'false');
    setSending(true);
    setErr(false);
    fetch('https://formsubmit.co/ajax/' + email, {
      method: 'POST',
      headers: { Accept: 'application/json' },
      body: data
    }).
    then((r) => {if (!r.ok) throw new Error('send failed');return r.json();}).
    then(() => {setSent(true);setKinds([]);form.reset();}).
    catch(() => {setErr(true);}).
    then(() => setSending(false));
  };
  return (
    <SectionView tag="When can we talk" num="" onBack={onBack}
    title="When can we <em>talk</em>?">
      <div className="contact-grid">
        <div className="contact-lead">
          <h3 className="reveal">I'm already curious about you</h3>
          <p className="reveal">I reply to most things within 3 looking-glass days. Well, it depends...</p>
          <div className="contact-direct reveal">
            Or reach me directly
            <button className={'em' + (copied ? ' copied' : '')} onClick={copyEmail}>
              {email} <Icon name={copied ? 'check' : 'copy'} size={16} />
            </button>
          </div>
        </div>
        <div>
          {sent ?
          <div className="confirm reveal in">
              <div className="ttl">Curiouser — your note landed.</div>
              <p>Thank you. I'll read it properly and write back, usually within two looking-glass days. If it's urgent, the email button copies my address.</p>
              <button className="again" onClick={() => setSent(false)}>Send another →</button>
            </div> :

          <form className="form" onSubmit={submitForm}>
              <div className="field"><label>Your name</label><input name="name" required placeholder="Who's asking?" /></div>
              <div className="field"><label>Email</label><input name="email" required type="email" placeholder="you@somewhere.com" /></div>
              <div className="field">
                <label>What's it about?</label>
                <div className="chip-row">
                  {projectTypes.map((k) =>
                <button type="button" key={k} className={'fchip' + (kinds.includes(k) ? ' on' : '')} onClick={() => toggle(k)}>{k}</button>
                )}
                </div>
              </div>
              <div className="field"><label>The message</label><textarea name="message" required placeholder="A sentence is plenty to start."></textarea></div>
              {err &&
            <p className="form-err">That didn't send. <a href={'mailto:' + email}>Email me directly</a> and it'll reach me just the same.</p>
            }
              <button className="submit" type="submit" disabled={sending}>{sending ? 'Sending…' : 'Send it'} <span className="arr"><Icon name="arrow-right" size={13} /></span></button>
            </form>
          }
        </div>
      </div>
    </SectionView>);

}

Object.assign(window, { SectionView, HowSection, WhichSection, WhoSection, WhySection, WhatSection, WhereSection, WhenSection });