/* global React */
const { useState, useEffect, useMemo, useRef } = React;

// ─── Logo / brand ────────────────────────────────────────────────────────────
function HeartMark({ size = 22, color = "currentColor" }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} aria-hidden="true">
      <path
        d="M12 21s-7.5-4.6-7.5-11A4.5 4.5 0 0 1 12 6a4.5 4.5 0 0 1 7.5 4c0 6.4-7.5 11-7.5 11Z"
        fill={color}
      />
    </svg>
  );
}

function Ribbon({ size = 32 }) {
  return (
    <svg viewBox="0 0 32 36" width={size} height={size * 36 / 32} aria-hidden="true">
      <path
        d="M16 32 C8 24 6 18 9 13 C11 9 14 8 16 12 C18 8 21 9 23 13 C26 18 24 24 16 32 Z"
        fill="none" stroke="#EC008C" strokeWidth="2.4"
      />
      <path d="M11 19 L13 22 M21 19 L19 22 M16 14 L16 30"
        stroke="#F5A9CB" strokeWidth="1.2" strokeLinecap="round" opacity="0.7" />
    </svg>
  );
}

function CheckGlyph() {
  return (
    <svg viewBox="0 0 16 16" fill="none">
      <path d="M3 8.5l3 3 7-7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function TopBar({ tenantSlug = "bco", sessionId, demoModeOn = true }) {
  return (
    <div className="topbar">
      <div className="topbar-left">
        <div className="topbar-logo">
          <span className="logo-mark"><HeartMark size={24} color="var(--pink)" /></span>
          <span>breastcancer.org</span>
        </div>
      </div>
      <div className="topbar-mid">
        SUPPORTING&nbsp;BREASTCANCER.ORG&nbsp;·&nbsp;WIMM LUNCHEON&nbsp;·&nbsp;MAY&nbsp;21
      </div>
      <div className="topbar-right">
        <span className="dot" />
        <span>Hosted by Ape Data · concept demo</span>
      </div>
    </div>
  );
}

// ─── Hero ────────────────────────────────────────────────────────────────────
function HeroScreen({ onStart }) {
  return (
    <div className="hero-frame fade-enter">
      <div className="hero-ribbon-block">
        <Ribbon size={26} />
        <span className="eyebrow">{window.BCO_BRANDING.eyebrow}</span>
      </div>
      <h1 className="hero">Tell us how <em>you'd</em><br/>like to support.</h1>
      <p className="sub" style={{ fontSize: 20, maxWidth: '54ch' }}>
        A minute of thoughtful questions. We'll match you to the breastcancer.org content,
        community, and partnership pathways that fit where you are.
      </p>
      <div className="q-footer">
        <button className="btn btn-primary" onClick={onStart}>
          Continue <span aria-hidden="true">→</span>
        </button>
        <span style={{ fontSize: 13, color: "var(--ink-3)" }}>~60–90 seconds · 7 questions</span>
      </div>
      <p className="hero-disclaimer">
        Hosted by Ape Data in support of breastcancer.org. Concept demo · your responses
        route only to breastcancer.org's partnerships team. No third-party data sharing.
      </p>

      <div className="hero-mosaic">
        <div className="mosaic-card">
          <div className="mosaic-k">FOR PARTNERSHIP LEADERS</div>
          <strong>Match your brand to the right program.</strong>
          Cause marketing, corporate giving, event sponsorship, advocacy.
        </div>
        <div className="mosaic-card">
          <div className="mosaic-k">FOR EDITORIAL</div>
          <strong>Sources, data, and the editorial calendar.</strong>
          Direct line to comms and the medical advisory board.
        </div>
        <div className="mosaic-card">
          <div className="mosaic-k">FOR PERSONAL</div>
          <strong>Resources for wherever you are.</strong>
          Peer community, clinical info, caregiver support.
        </div>
      </div>
    </div>
  );
}

// ─── Generic question screen ────────────────────────────────────────────────
function QuestionScreen({ q, value, onChange, onNext, onBack, canSkip, isMulti, isFinalOfBranch }) {
  const [local, setLocal] = useState(value ?? (isMulti ? [] : ""));
  useEffect(() => { setLocal(value ?? (isMulti ? [] : "")); }, [q.id]);

  // compose: multi text-field
  const [compose, setCompose] = useState(value || {});
  useEffect(() => { setCompose(value || {}); }, [q.id]);

  const isCards = q.kind === "cards";
  const isMultiKind = q.kind === "multi";
  const isText = q.kind === "text";
  const isCompose = q.kind === "compose";

  const select = (id) => {
    if (isMultiKind) {
      const next = local.includes(id) ? local.filter(x => x !== id) : [...local, id];
      // Mutex handling — if mutex item is the one being toggled
      const mutexId = q.mutexId;
      let final = next;
      if (mutexId) {
        const opt = q.options.find(o => o.id === id);
        if (opt?.mutex) {
          // Toggling the mutex item: if selecting, clear all others
          final = next.includes(id) ? [id] : [];
        } else if (next.includes(mutexId)) {
          final = next.filter(x => x !== mutexId);
        }
      }
      setLocal(final);
      onChange(final);
    } else {
      setLocal(id);
      onChange(id);
    }
  };

  const isFilled = isText
    ? !!String(local).trim()
    : isCompose
      ? q.fields.every(f => String(compose[f.id] || "").trim())
      : isMultiKind ? local.length > 0 : !!local;

  const canContinue = q.optional || isFilled;

  const cardsTwoCol = isCards && q.options.length > 5;
  const optsClass = `cards ${cardsTwoCol ? "cols-2" : ""} stagger`;

  return (
    <div className="frame fade-enter">
      <div className="frame-inner">
        <div className="eyebrow">{q.eyebrow}</div>
        <h2 className="q-title">{q.title}</h2>
        {q.sub && <p className="sub">{q.sub}</p>}

        {(isCards || isMultiKind) && (
          <div className={optsClass}>
            {q.options.map(o => {
              const selected = isMultiKind ? local.includes(o.id) : local === o.id;
              return (
                <button
                  key={o.id}
                  className={`card-opt ${selected ? "selected" : ""} ${isMultiKind ? "multi" : ""} ${o.quiet ? "quiet" : ""}`}
                  onClick={() => select(o.id)}
                  type="button"
                >
                  {!isMultiKind && o.glyph && <span className="card-opt-glyph">{o.glyph}</span>}
                  <span className="card-opt-text">
                    <span className="card-opt-label">{o.label}</span>
                    {o.hint && <span className="card-opt-hint">{o.hint}</span>}
                  </span>
                  <span className="check"><CheckGlyph /></span>
                </button>
              );
            })}
          </div>
        )}

        {isText && (
          <input
            className="text-field"
            type="text"
            placeholder={q.placeholder}
            value={local}
            autoFocus
            onChange={(e) => { setLocal(e.target.value); onChange(e.target.value); }}
            onKeyDown={(e) => { if (e.key === "Enter" && canContinue) onNext(); }}
          />
        )}

        {isCompose && (
          <div className="compose-fields">
            {q.fields.map(f => (
              <div key={f.id}>
                <div className="field-label">{f.label}</div>
                <input
                  className="text-field"
                  type="text"
                  placeholder={f.placeholder}
                  value={compose[f.id] || ""}
                  onChange={(e) => {
                    const next = { ...compose, [f.id]: e.target.value };
                    setCompose(next);
                    onChange(next);
                  }}
                />
              </div>
            ))}
          </div>
        )}

        <div className="q-footer">
          <button className="btn btn-primary" onClick={onNext} disabled={!canContinue}>
            Continue <span aria-hidden="true">→</span>
          </button>
          <button className="btn btn-link" onClick={onBack}>← Back</button>
          {(q.optional && !isFilled) && (
            <button className="btn btn-link optional-skip" onClick={() => onNext()}>
              Skip this one
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Email capture ──────────────────────────────────────────────────────────
function EmailScreen({ value, onChange, onSubmit, onBack }) {
  const [v, setV] = useState(value || {});
  useEffect(() => { setV(value || {}); }, []);
  const update = (key, val) => {
    const next = { ...v, [key]: val };
    setV(next); onChange(next);
  };
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.email || "");
  const canSend = emailOk && v.consent;
  return (
    <div className="frame fade-enter">
      <div className="frame-inner">
        <div className="eyebrow">QUESTION 08 / IDENTITY</div>
        <h2 className="q-title">One step left — where should we route this?</h2>
        <p className="sub">
          Email so breastcancer.org's partnerships team can follow up.
          We won't share your data, and you can delete your record anytime.
        </p>

        <div className="email-grid stagger">
          <input
            className="text-field"
            type="email"
            placeholder="your@email.com"
            autoFocus
            value={v.email || ""}
            onChange={(e) => update("email", e.target.value)}
          />
          <div className="email-row">
            <input
              className="text-field"
              type="text"
              placeholder="Your name (optional)"
              value={v.name || ""}
              onChange={(e) => update("name", e.target.value)}
            />
            <input
              className="text-field"
              type="tel"
              placeholder="Mobile (optional)"
              value={v.mobile || ""}
              onChange={(e) => update("mobile", e.target.value)}
            />
          </div>

          <div className="consent-block">
            <button
              type="button"
              className={`checkbox-pink ${v.consent ? "on" : ""}`}
              aria-pressed={!!v.consent}
              onClick={() => update("consent", !v.consent)}
            ><CheckGlyph /></button>
            <span>
              I agree to be contacted by breastcancer.org's partnerships team. I understand my
              answers may be associated with my email and stored according to breastcancer.org's{" "}
              <a href="https://www.breastcancer.org/policies/health-data-privacy-policy" target="_blank" rel="noreferrer">
                Consumer Health Data Privacy Policy
              </a>.
            </span>
          </div>
        </div>

        <div className="q-footer">
          <button className="btn btn-pink" onClick={onSubmit} disabled={!canSend}>
            Lock it in <span aria-hidden="true">→</span>
          </button>
          <button className="btn btn-link" onClick={onBack}>← Back</button>
        </div>
      </div>
    </div>
  );
}

// ─── Celebration ────────────────────────────────────────────────────────────
function ArticleArt({ variant = "v1" }) {
  // simple subtle iconographic SVG per card — no stock imagery
  const icons = {
    v1: <path d="M12 32 C4 24 4 16 10 14 C14 13 16 16 16 16 C16 16 18 13 22 14 C28 16 28 24 20 32 Z" fill="#fff"/>,
    v2: <g><circle cx="16" cy="14" r="6" fill="#fff"/><path d="M6 32 C6 24 10 22 16 22 C22 22 26 24 26 32" fill="#fff"/></g>,
    v3: <g><path d="M6 20 L26 20 M6 14 L26 14 M6 26 L20 26" stroke="#fff" strokeWidth="2.4" strokeLinecap="round"/></g>,
  };
  return (
    <svg viewBox="0 0 32 36" width="56" height="56" aria-hidden="true">
      {icons[variant]}
    </svg>
  );
}

function CelebrationScreen({ state, onShare, onReset }) {
  const articles = window.BCO_ARTICLES[state.branch] || window.BCO_ARTICLES.light;
  const cta = window.BCO_CTA(state);
  const firstName = (state.name || "").split(" ")[0];
  return (
    <div className="celebrate fade-enter">
      {/* Beat 1 */}
      <div className="cel-beat cel-thanks">
        <span className="cel-beat-num">BEAT 01</span>
        <div className="cel-glyph"><Ribbon size={40} /></div>
        <h1>Thank you {firstName ? <em>{firstName}</em> : <em>for being here</em>}.</h1>
        <p className="cel-sub">
          Your responses are routing to breastcancer.org's partnerships team now.
          Drawing closes — wait, no drawing. Just gratitude.
        </p>
      </div>

      {/* Beat 2 */}
      <div className="cel-beat">
        <span className="cel-beat-num">BEAT 02</span>
        <div className="eyebrow">MATCHED RESOURCES · CURATED FOR YOU</div>
        <h2 className="q-title" style={{ fontSize: 32, marginTop: 8 }}>
          Three things from the editorial library that fit where you are.
        </h2>
        <div className="cel-articles stagger">
          {articles.map((a, i) => (
            <a
              className="cel-article"
              key={i}
              href={a.href || "#"}
              target="_blank"
              rel="noopener noreferrer"
              style={{ textDecoration: "none", color: "inherit" }}
            >
              <div className={`cel-article-img v${i + 1}`}>
                <ArticleArt variant={`v${i + 1}`} />
              </div>
              <div className="cel-article-body">
                <div className="cel-article-kicker">{a.kicker}</div>
                <div className="cel-article-title">{a.title}</div>
                <div className="cel-article-meta">
                  <span>{a.read}</span>
                  <span className="cel-article-tag">{a.tag} ↗</span>
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>

      {/* Beat 3 — Primary cultivation CTA (adaptive) */}
      <div className="cel-beat">
        <span className="cel-beat-num">BEAT 03</span>
        <div className="cel-cta-card">
          <div className="cel-cta-kicker">{cta.kicker}</div>
          <div className="cel-cta-title">{cta.title}</div>
          <div className="cel-cta-sub">{cta.sub}</div>
          <div className="cel-cta-meta">
            <strong>{cta.contact}</strong>
            {cta.detail && <span> · {cta.detail}</span>}
          </div>
          <div className="cel-cta-row">
            <button className="btn btn-on-dark">{cta.cta} <span aria-hidden="true">→</span></button>
            <button className="btn btn-dark-ghost" onClick={onReset}>Not now</button>
          </div>
        </div>
      </div>

      {/* Beat 4 — Share */}
      <div className="cel-beat">
        <span className="cel-beat-num">BEAT 04</span>
        <div className="cel-share">
          <div className="cel-share-title">Bring someone else into this conversation.</div>
          <div className="cel-share-sub">
            Forward this to a colleague who'd want to be part of breastcancer.org's work.
          </div>
          <div className="share-row">
            {["Messages", "WhatsApp", "X", "LinkedIn DM", "Email", "Copy link"].map(s => (
              <button key={s} className="share-chip" onClick={() => onShare(s)}>
                <ShareGlyph kind={s} /> {s}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function ShareGlyph({ kind }) {
  const map = {
    "Messages": "💬", "WhatsApp": "◍", "X": "𝕏", "LinkedIn DM": "in", "Email": "✉", "Copy link": "⎘"
  };
  return <span style={{ fontFamily: kind === "LinkedIn DM" ? "var(--font-sans)" : "inherit", fontWeight: 600, color: "var(--pink-deep)", fontSize: 12 }}>{map[kind] || "·"}</span>;
}

Object.assign(window, {
  HeartMark, Ribbon, TopBar, HeroScreen, QuestionScreen, EmailScreen, CelebrationScreen
});
