/* global React */
// FIXiQ explainer — scenes 1–4 (problem, capture, structure, connect).
// Exposes window.FxScenesA + window.FX helpers.
(function () {
  const { Sprite, useSprite } = window;

  // ---- shared helpers ----
  const C = {
    navy: '#1E2A3F', ink: '#16202F', paper: '#F7F9FB', white: '#FFFFFF',
    em: '#1C6B55', em50: '#EEF5F1', em100: '#DCEBE5', em300: '#7FBEAB',
    slate2: '#D8DEE6', slate4: '#8696A8', slate5: '#5A6B82', slate6: '#41526B',
    gold: '#C9A961', ochre: '#9A6B1F', ochreBg: '#F6EEDD', brick: '#A23E2C', brickBg: '#F6E9E5',
    sans: "-apple-system,'Helvetica Neue',Arial,'Segoe UI',sans-serif",
    serif: 'Georgia,serif', mono: 'ui-monospace,Menlo,Consolas,monospace',
  };
  const clamp01 = (t) => Math.min(Math.max(t, 0), 1);
  const EZ = (t) => 1 - Math.pow(1 - clamp01(t), 3); // easeOutCubic
  const at = (lt, start, dur = 0.6) => EZ((lt - start) / dur);
  const fadeUp = (lt, start, dur = 0.6, dist = 22) => {
    const p = at(lt, start, dur);
    return { opacity: p, transform: `translateY(${(1 - p) * dist}px)` };
  };
  const sceneFade = (lt, total, d = 0.55) => Math.min(EZ(lt / d), EZ((total - lt) / d));

  function FxCaption({ lt, step, text, start = 0.5 }) {
    return (
      <div style={{ position: 'absolute', left: 64, bottom: 46, ...fadeUp(lt, start) }}>
        {step && <div style={{ fontFamily: C.mono, fontSize: 13, letterSpacing: 2, color: C.em, marginBottom: 7, ...fadeUp(lt, start) }}>{step}</div>}
        <div style={{ fontFamily: C.serif, fontSize: 30, fontWeight: 700, color: C.navy, ...fadeUp(lt, start + 0.12) }}>{text}</div>
      </div>
    );
  }

  function FxBrand({ small }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
        <img src={(window.__resources && window.__resources.fixiqIcon) || '../assets/fixiq-icon.svg'} width={small ? 22 : 30} height={small ? 22 : 30} alt="" />
        <span style={{ fontFamily: C.sans, fontWeight: 800, fontSize: small ? 17 : 22, letterSpacing: '-0.3px' }}>
          <span style={{ color: C.navy }}>FIX</span><span style={{ color: C.em }}>iQ</span>
        </span>
      </div>
    );
  }

  function FxChip({ label, sub, x, y, r, lt, start, tone }) {
    const p = at(lt, start, 0.7);
    const drift = Math.sin((lt - start) * 0.9 + x) * 4;
    return (
      <div style={{
        position: 'absolute', left: x, top: y, width: 196,
        transform: `rotate(${r}deg) translateY(${(1 - p) * 30 + drift}px) scale(${0.92 + 0.08 * p})`,
        opacity: p, background: tone || C.white, border: `1px solid ${C.slate2}`,
        borderRadius: 6, padding: '12px 14px', boxShadow: '0 2px 6px rgba(16,32,47,0.08)',
        fontFamily: C.sans,
      }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: C.slate4, marginBottom: 4 }}>{label}</div>
        <div style={{ fontSize: 12.5, color: C.slate6, lineHeight: 1.4 }}>{sub}</div>
      </div>
    );
  }

  // ============================ SCENE 1 — the problem (0–11s)
  function SceneProblem() {
    const { localTime: lt } = useSprite();
    const total = 26.5;
    const zoom = 1 + 0.05 * clamp01(lt / total);
    const chips = [
      ['Email', '“Re: Re: Fwd: ceiling stain — see attached…”', 80, 120, -3, 0.4],
      ['SMS', '“hi water coming in again, unit 36”', 330, 78, 2, 0.9],
      ['PDF · Quote', 'Vendor estimate — $4,860, sealant repair', 590, 130, -2, 1.4],
      ['Photo', 'IMG_2214.jpg — ceiling, living room', 860, 84, 3, 1.9],
      ['Board email', '“Has this happened before? Need history.”', 150, 300, 2, 2.4],
      ['Reserve fund study', 'Building envelope — window heads, p.41', 920, 290, -3, 2.9],
      ['Old record', '2021 repair… filed by previous manager', 520, 330, 1, 3.4],
      ['Phone note', 'Called twice — no access until Friday', 700, 470, -2, 3.9],
      ['Minutes', 'Board meeting #14 — deferred decision', 230, 480, 3, 4.4],
    ];
    return (
      <div style={{ position: 'absolute', inset: 0, background: C.paper, opacity: sceneFade(lt, total) }}>
        <div style={{ position: 'absolute', inset: 0, transform: `scale(${zoom})`, transformOrigin: '50% 45%' }}>
          {chips.map((c, i) => <FxChip key={i} label={c[0]} sub={c[1]} x={c[2]} y={c[3]} r={c[4]} start={c[5]} lt={lt} />)}
        </div>
        <div style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 220, background: 'linear-gradient(rgba(247,249,251,0.95), rgba(247,249,251,0))' }}></div>
        <div style={{ position: 'absolute', left: 64, top: 52, ...fadeUp(lt, 0.2) }}><FxBrand /></div>
        <div style={{ position: 'absolute', left: 64, bottom: 46, maxWidth: 760 }}>
          <div style={{ fontFamily: C.serif, fontSize: 44, fontWeight: 700, color: C.navy, lineHeight: 1.15, ...fadeUp(lt, 5.6) }}>Property knowledge is scattered.</div>
          <div style={{ fontFamily: C.sans, fontSize: 19, color: C.slate5, marginTop: 10, ...fadeUp(lt, 6.6) }}>The documents exist — in inboxes, texts, PDFs, and a previous manager's memory.</div>
        </div>
      </div>
    );
  }

  // ============================ SCENE 2 — capture (11–20s)
  function SceneCapture() {
    const { localTime: lt } = useSprite();
    const total = 16;
    const dotsOn = lt > 1.0 && lt < 2.2;
    return (
      <div style={{ position: 'absolute', inset: 0, background: C.paper, opacity: sceneFade(lt, total) }}>
        <div style={{ position: 'absolute', left: 64, top: 52 }}><FxBrand /></div>
        {/* phone-ish thread */}
        <div style={{ position: 'absolute', left: 410, top: 120, width: 460, ...fadeUp(lt, 0.3) }}>
          <div style={{ background: C.white, border: `1px solid ${C.slate2}`, borderRadius: 12, overflow: 'hidden', boxShadow: '0 8px 24px rgba(16,32,47,0.12)' }}>
            <div style={{ padding: '12px 18px', borderBottom: `1px solid ${C.slate2}`, fontFamily: C.sans, fontSize: 13.5, fontWeight: 700, color: C.navy, display: 'flex', justifyContent: 'space-between' }}>
              <span>Unit 36 · Resident</span><span style={{ color: C.slate4, fontWeight: 500 }}>SMS</span>
            </div>
            <div style={{ padding: '18px 18px 22px', minHeight: 120 }}>
              {dotsOn && (
                <div style={{ display: 'inline-flex', gap: 5, background: '#EDF0F4', borderRadius: 14, padding: '10px 14px' }}>
                  {[0, 1, 2].map(i => <span key={i} style={{ width: 7, height: 7, borderRadius: 99, background: C.slate4, opacity: 0.4 + 0.6 * Math.abs(Math.sin(lt * 5 + i)) }}></span>)}
                </div>
              )}
              {lt >= 2.2 && (
                <div style={{ background: '#EDF0F4', borderRadius: '14px 14px 14px 4px', padding: '13px 16px', fontFamily: C.sans, fontSize: 16.5, color: C.ink, lineHeight: 1.5, maxWidth: 360, ...fadeUp(lt, 2.2, 0.5, 10) }}>
                  “Water is leaking through my ceiling again. I think this happened before.”
                </div>
              )}
              {lt >= 3.6 && (
                <div style={{ marginTop: 10, fontFamily: C.mono, fontSize: 11.5, color: C.slate4, ...fadeUp(lt, 3.6, 0.5, 8) }}>2 photos attached · 8:42 am</div>
              )}
            </div>
          </div>
          {/* intake channels */}
          <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginTop: 16, ...fadeUp(lt, 4.6) }}>
            {['SMS', 'Email', 'Web form', 'Voice'].map((ch, i) => (
              <span key={ch} style={{ fontFamily: C.sans, fontSize: 12.5, fontWeight: 600, color: ch === 'SMS' ? C.white : C.slate6, background: ch === 'SMS' ? C.em : C.white, border: `1px solid ${ch === 'SMS' ? C.em : C.slate2}`, borderRadius: 4, padding: '5px 12px', ...fadeUp(lt, 4.6 + i * 0.15) }}>{ch}</span>
            ))}
          </div>
        </div>
        <FxCaption lt={lt} step="CAPTURE" text="Captured the moment it's reported — text, email, web form, or phone." start={7} />
      </div>
    );
  }

  // ============================ SCENE 3 — structure (20–33s)
  function FxField({ k, v, lt, start, strong }) {
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '7.5px 0', borderBottom: `1px solid #EDF0F4`, fontFamily: C.sans, fontSize: 14.5, ...fadeUp(lt, start, 0.45, 10) }}>
        <span style={{ color: C.slate5, flex: 'none', whiteSpace: 'nowrap' }}>{k}</span>
        <span style={{ color: strong ? C.em : C.ink, fontWeight: 600, textAlign: 'right', whiteSpace: 'nowrap' }}>{v}</span>
      </div>
    );
  }
  function SceneStructure() {
    const { localTime: lt } = useSprite();
    const total = 16.5;
    const fields = [
      ['Property', 'Crestview Manor', 1.6], ['Unit / location', '36 · Living room ceiling', 2.1],
      ['Issue type', 'Water ingress', 2.6], ['Water involved', 'Yes — staining visible', 3.1],
      ['Urgency', 'Review required', 3.6], ['Photos', '2 attached', 4.1],
      ['Prior occurrence', 'Suspected — checking memory', 4.6, true], ['Access', 'After 4 pm weekdays', 5.1],
    ];
    return (
      <div style={{ position: 'absolute', inset: 0, background: C.paper, opacity: sceneFade(lt, total) }}>
        <div style={{ position: 'absolute', left: 64, top: 52 }}><FxBrand /></div>
        {/* small source message, docked */}
        <div style={{ position: 'absolute', left: 110, top: 170, width: 300, opacity: at(lt, 0.2), transform: `scale(${0.96 + 0.04 * at(lt, 0.2)})` }}>
          <div style={{ background: '#EDF0F4', borderRadius: '14px 14px 14px 4px', padding: '12px 14px', fontFamily: C.sans, fontSize: 13.5, color: C.slate6, lineHeight: 1.5 }}>
            “Water is leaking through my ceiling again. I think this happened before.”
          </div>
          <div style={{ fontFamily: C.mono, fontSize: 11, color: C.slate4, marginTop: 8 }}>Unit 36 · SMS · 8:42 am</div>
        </div>
        {/* arrow */}
        <div style={{ position: 'absolute', left: 432, top: 300, fontFamily: C.sans, fontSize: 30, color: C.em, opacity: at(lt, 0.9) }}>→</div>
        {/* structured card */}
        <div style={{ position: 'absolute', left: 500, top: 110, width: 480, ...fadeUp(lt, 0.8, 0.7, 26) }}>
          <div style={{ background: C.white, border: `1px solid ${C.slate2}`, borderTop: `3px solid ${C.em}`, borderRadius: 8, boxShadow: '0 8px 24px rgba(16,32,47,0.12)', padding: '18px 22px 14px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <span style={{ fontFamily: C.mono, fontSize: 12.5, fontWeight: 600, color: C.em, background: C.em50, border: `1px solid ${C.em100}`, borderRadius: 3, padding: '2px 8px', whiteSpace: 'nowrap' }}>ISS-204</span>
              <span style={{ fontFamily: C.sans, fontSize: 16, fontWeight: 700, color: C.navy, whiteSpace: 'nowrap' }}>Water ingress — ceiling</span>
              <span style={{ marginLeft: 'auto', fontFamily: C.sans, fontSize: 11.5, fontWeight: 700, color: C.ochre, background: C.ochreBg, borderRadius: 3, padding: '3px 8px', opacity: at(lt, 5.6) }}>Review</span>
            </div>
            {fields.map(f => <FxField key={f[0]} k={f[0]} v={f[1]} lt={lt} start={f[2]} strong={f[3]} />)}
          </div>
        </div>
        <FxCaption lt={lt} step="STRUCTURE" text="A structured issue record — and the right next questions." start={7} />
      </div>
    );
  }

  // ============================ SCENE 4 — connect (33–46s)
  function FxMem({ id, title, sub, lt, start, y }) {
    const p = at(lt, start, 0.55);
    return (
      <div style={{ position: 'absolute', left: 0, top: y, width: 380, opacity: p, transform: `translateX(${(1 - p) * 26}px)` }}>
        <div style={{ background: C.white, border: `1px solid ${C.slate2}`, borderLeft: `3px solid ${C.em}`, borderRadius: '0 6px 6px 0', padding: '11px 14px', fontFamily: C.sans }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
            <span style={{ fontFamily: C.mono, fontSize: 11, fontWeight: 600, color: C.em }}>{id}</span>
            <span style={{ fontSize: 13.5, fontWeight: 700, color: C.navy, whiteSpace: 'nowrap' }}>{title}</span>
          </div>
          <div style={{ fontSize: 12, color: C.slate5, marginTop: 3, lineHeight: 1.45 }}>{sub}</div>
        </div>
      </div>
    );
  }
  function SceneConnect() {
    const { localTime: lt } = useSprite();
    const total = 19;
    const mems = [
      ['REC-088', '2021 leak — same window head', 'Sealant repair · Apex Restoration', 1.6, 0],
      ['VND-112', '2023 vendor site visit', '“Recommend envelope review if recurs”', 2.5, 78],
      ['DOC-041', 'Reserve fund study · p.41', 'Building envelope — window heads flagged', 3.4, 156],
      ['BRD-019', 'Board minutes #14', 'Envelope assessment deferred to 2026', 4.3, 234],
    ];
    const scanning = lt > 0.6 && lt < 1.7;
    return (
      <div style={{ position: 'absolute', inset: 0, background: C.paper, opacity: sceneFade(lt, total) }}>
        <div style={{ position: 'absolute', left: 64, top: 52 }}><FxBrand /></div>
        {/* issue card docked left */}
        <div style={{ position: 'absolute', left: 110, top: 150, width: 360, opacity: at(lt, 0.15) }}>
          <div style={{ background: C.white, border: `1px solid ${C.slate2}`, borderTop: `3px solid ${C.em}`, borderRadius: 8, padding: '15px 18px', boxShadow: '0 2px 6px rgba(16,32,47,0.08)' }}>
            <div style={{ display: 'flex', gap: 9, alignItems: 'center', fontFamily: C.sans }}>
              <span style={{ fontFamily: C.mono, fontSize: 12, fontWeight: 600, color: C.em, background: C.em50, border: `1px solid ${C.em100}`, borderRadius: 3, padding: '2px 7px' }}>ISS-204</span>
              <span style={{ fontSize: 14.5, fontWeight: 700, color: C.navy, whiteSpace: 'nowrap' }}>Water ingress — Unit 36</span>
            </div>
            <div style={{ marginTop: 10, fontFamily: C.mono, fontSize: 11.5, color: scanning ? C.em : C.slate4 }}>
              {scanning ? 'searching property memory…' : lt >= 1.7 ? '4 connected records found' : ' '}
            </div>
          </div>
        </div>
        {/* connector lines */}
        {mems.map((m, i) => (
          <div key={i} style={{ position: 'absolute', left: 470, top: 192 + (i === 0 ? 0 : 0) + 22 + m[4] * 0 , width: 0 }}></div>
        ))}
        <svg width="180" height="360" style={{ position: 'absolute', left: 468, top: 150 }}>
          {mems.map((m, i) => {
            const p = at(lt, m[3] - 0.25, 0.5);
            return <path key={i} d={`M 4 60 C 80 60, 90 ${36 + m[4]}, 172 ${36 + m[4]}`} fill="none" stroke={C.em300} strokeWidth="1.6" strokeDasharray="220" strokeDashoffset={220 * (1 - p)} />;
          })}
        </svg>
        {/* memory records */}
        <div style={{ position: 'absolute', left: 648, top: 168 }}>
          <div style={{ fontFamily: C.sans, fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: 'uppercase', color: C.em, marginBottom: 14, ...fadeUp(lt, 1.2) }}>Property memory</div>
          <div style={{ position: 'relative' }}>
            {mems.map(m => <FxMem key={m[0]} id={m[0]} title={m[1]} sub={m[2]} lt={lt} start={m[3]} y={m[4] + 20} />)}
          </div>
        </div>
        <FxCaption lt={lt} step="CONNECT" text="Connected to the building's history — every claim cited." start={7} />
        <div style={{ position: 'absolute', right: 70, bottom: 150, maxWidth: 400, textAlign: 'right', fontFamily: C.serif, fontStyle: 'italic', fontSize: 17.5, lineHeight: 1.45, color: C.em, ...fadeUp(lt, 8.4) }}>“A leak is not just a leak if it happened three times before.”</div>
      </div>
    );
  }

  window.FX = { C, EZ, at, fadeUp, sceneFade, FxCaption, FxBrand };
  window.FxScenesA = { SceneProblem, SceneCapture, SceneStructure, SceneConnect };
})();
