// MEGALIS — 3-question intake modal. Appears 3s after load, slides between steps,
// thanks the visitor, then dismisses itself. Answer is kept in localStorage so it
// only ever asks once per visitor.

const surveyStyles = `
  .sv-backdrop {
    position: fixed;
    inset: 0;
    z-index: 90;
    display: grid;
    place-items: center;
    padding: 24px;
    background: color-mix(in oklab, #000 62%, transparent);
    backdrop-filter: blur(8px) saturate(120%);
    -webkit-backdrop-filter: blur(8px) saturate(120%);
    opacity: 0;
    transition: opacity 0.5s var(--easing);
  }
  .sv-backdrop[data-in="true"]  { opacity: 1; }
  .sv-backdrop[data-out="true"] { opacity: 0; pointer-events: none; }

  .sv-card {
    position: relative;
    width: min(560px, 100%);
    background: var(--bg);
    border: 1px solid var(--line);
    overflow: hidden;
    transform: translateY(18px) scale(0.985);
    transition: transform 0.55s var(--easing);
  }
  .sv-backdrop[data-in="true"] .sv-card  { transform: none; }
  .sv-backdrop[data-out="true"] .sv-card { transform: translateY(10px) scale(0.99); }

  .sv-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--line);
  }
  .sv-brand {
    display: flex;
    align-items: center;
    gap: 10px;
    font-family: var(--font-mono);
    font-size: 10px;
    letter-spacing: 0.2em;
    text-transform: uppercase;
    color: var(--fg-3);
  }
  .sv-brand .dot {
    width: 7px; height: 7px;
    background: var(--accent);
    transform: rotate(45deg);
  }
  .sv-skip {
    font-family: var(--font-mono);
    font-size: 13px;
    letter-spacing: 0.2em;
    text-transform: uppercase;
    color: #fff;
    background: none;
    border: 0;
    padding: 6px 2px;
    cursor: pointer;
    transition: color 0.25s var(--easing), letter-spacing 0.25s var(--easing);
  }
  .sv-skip:hover { color: var(--accent); letter-spacing: 0.26em; }

  .sv-body { padding: 26px 24px 24px; }

  .sv-intro {
    font-family: var(--font-mono);
    font-size: 10.5px;
    letter-spacing: 0.16em;
    text-transform: uppercase;
    color: var(--fg-3);
    margin-bottom: 22px;
    text-wrap: pretty;
  }

  .sv-steps { position: relative; overflow: hidden; }
  .sv-step {
    display: flex;
    flex-direction: column;
    gap: 18px;
    transition: transform 0.55s var(--easing), opacity 0.4s var(--easing);
  }
  .sv-step[data-state="current"] { transform: none; opacity: 1; }
  .sv-step[data-state="past"]    { position: absolute; inset: 0; transform: translateX(-32px); opacity: 0; pointer-events: none; }
  .sv-step[data-state="next"]    { position: absolute; inset: 0; transform: translateX(32px);  opacity: 0; pointer-events: none; }

  .sv-qnum {
    font-family: var(--font-mono);
    font-size: 9.5px;
    letter-spacing: 0.2em;
    color: var(--accent);
  }
  .sv-q {
    font-family: var(--font-display);
    font-weight: 700;
    font-size: clamp(22px, 3vw, 30px);
    letter-spacing: -0.025em;
    line-height: 1.05;
    margin: 6px 0 0;
    text-wrap: pretty;
  }
  body[data-lang="ja"] .sv-q { font-family: var(--font-jp); letter-spacing: 0; }

  .sv-opts { display: flex; flex-wrap: wrap; gap: 8px; }
  .sv-opt {
    font-family: var(--font-mono);
    font-size: 11px;
    letter-spacing: 0.12em;
    text-transform: uppercase;
    color: var(--fg-2);
    background: transparent;
    border: 1px solid var(--line);
    padding: 11px 15px;
    cursor: pointer;
    transition: border-color 0.25s var(--easing), color 0.25s var(--easing), background 0.25s var(--easing);
  }
  .sv-opt:hover { border-color: var(--fg-3); color: var(--fg); }
  .sv-opt[data-sel="true"] {
    background: var(--accent);
    border-color: var(--accent);
    color: var(--accent-fg);
  }
  .sv-other {
    width: 100%;
    font-family: var(--font-mono);
    font-size: 11px;
    letter-spacing: 0.08em;
    color: var(--fg);
    background: var(--bg-2);
    border: 1px solid var(--line);
    padding: 11px 13px;
    margin-top: -6px;
    outline: none;
    transition: border-color 0.25s var(--easing);
  }
  .sv-other::placeholder { color: var(--fg-3); letter-spacing: 0.12em; text-transform: uppercase; font-size: 10px; }
  .sv-other:focus { border-color: var(--accent); }

  .sv-foot {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    margin-top: 4px;
  }
  .sv-nav { display: flex; align-items: center; gap: 8px; }
  .sv-hint {
    font-family: var(--font-mono);
    font-size: 9.5px;
    letter-spacing: 0.16em;
    text-transform: uppercase;
    color: var(--fg-3);
  }
  .sv-subhint { margin-top: 10px; }
  .sv-next {
    font-family: var(--font-mono);
    font-size: 11px;
    letter-spacing: 0.2em;
    text-transform: uppercase;
    color: var(--accent-fg);
    background: var(--accent);
    border: 1px solid var(--accent);
    padding: 11px 20px;
    cursor: pointer;
    transition: opacity 0.25s var(--easing), letter-spacing 0.25s var(--easing);
  }
  .sv-next:hover:not(:disabled) { letter-spacing: 0.26em; }
  .sv-next:disabled { opacity: 0.34; cursor: not-allowed; }
  .sv-back {
    font-family: var(--font-mono);
    font-size: 11px;
    letter-spacing: 0.2em;
    text-transform: uppercase;
    color: var(--fg-2);
    background: transparent;
    border: 1px solid var(--line);
    padding: 11px 18px;
    cursor: pointer;
    transition: border-color 0.25s var(--easing), color 0.25s var(--easing), opacity 0.25s var(--easing);
  }
  .sv-back:hover:not(:disabled) { border-color: var(--fg-3); color: var(--fg); }
  .sv-back:disabled { opacity: 0.3; cursor: not-allowed; }

  /* progress */
  .sv-prog { display: flex; gap: 5px; padding: 0 24px 20px; }
  .sv-prog i {
    height: 2px;
    flex: 1;
    background: var(--line);
    transition: background 0.45s var(--easing);
  }
  .sv-prog i[data-on="true"] { background: var(--accent); }

  /* thank-you */
  .sv-thanks {
    display: grid;
    place-items: center;
    text-align: center;
    gap: 14px;
    padding: 46px 30px 50px;
    opacity: 0;
    transition: opacity 2.5s var(--easing);
  }
  .sv-thanks[data-in="true"] { opacity: 1; }
  .sv-thanks .mark {
    width: 12px; height: 12px;
    background: var(--accent);
    transform: rotate(45deg);
    margin-bottom: 4px;
  }
  .sv-thanks p {
    font-family: var(--font-display);
    font-weight: 700;
    font-size: clamp(19px, 2.4vw, 26px);
    letter-spacing: -0.02em;
    line-height: 1.2;
    margin: 0;
    max-width: 30ch;
    text-wrap: pretty;
  }

  @media (max-width: 520px) {
    .sv-body { padding: 22px 18px 20px; }
    .sv-head { padding: 14px 16px; }
    .sv-prog { padding: 0 18px 16px; }
  }
  @media (prefers-reduced-motion: reduce) {
    .sv-backdrop, .sv-card, .sv-step, .sv-thanks { transition-duration: 0.01ms !important; }
  }
`;

const SURVEY_QUESTIONS = [
  {
    id: "role",
    q: "Who are you?",
    multi: false,
    options: ["Artist", "Director", "Producer", "Student", "Just visiting"],
  },
  {
    id: "based",
    q: "Where are you based?",
    multi: false,
    options: ["United States of America", "Japan", "France", "Canada",
              "The United Kingdom", "South Korea", "India", "Thailand", "Other"],
  },
  {
    id: "industry",
    q: "What industry are you in?",
    multi: true,
    options: ["Movie / TV-show", "VOD", "Animation", "Gaming", "Advertising",
              "VFX", "All", "Other"],
  },
];

function Survey({ delay = 3000 }) {
  const [phase, setPhase] = React.useState("hidden"); // hidden | asking | thanks | gone
  const [shown, setShown] = React.useState(false);
  const [leaving, setLeaving] = React.useState(false);
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [otherText, setOtherText] = React.useState("");
  const timers = React.useRef([]);

  const track = (fn, ms) => { const id = setTimeout(fn, ms); timers.current.push(id); return id; };
  React.useEffect(() => () => timers.current.forEach(clearTimeout), []);

  React.useEffect(() => {
    // TEMP: show on every page load. Restore the once-per-visitor check when asked.
    const id = setTimeout(() => { setPhase("asking"); requestAnimationFrame(() => setShown(true)); }, delay);
    return () => clearTimeout(id);
  }, [delay]);

  const persist = (data) => {
    try { localStorage.setItem("megalis:survey", JSON.stringify(data)); } catch (e) {}
  };

  const close = () => {
    setLeaving(true);
    track(() => setPhase("gone"), 600);
  };

  const skip = () => { persist({ skipped: true }); close(); };

  const finish = (final) => {
    persist(final);
    setPhase("thanks");
    // fade in over 2.5s, then dismiss the window right after
    track(() => close(), 2700);
  };

  const answer = (qi, value) => {
    const q = SURVEY_QUESTIONS[qi];
    if (q.multi) {
      setAnswers((a) => {
        const cur = a[q.id] || [];
        return { ...a, [q.id]: cur.includes(value) ? cur.filter((v) => v !== value) : [...cur, value] };
      });
      return;
    }
    const next = { ...answers, [q.id]: value };
    setAnswers(next);
    if (qi < SURVEY_QUESTIONS.length - 1) track(() => setStep(qi + 1), 240);
    else track(() => finish(next), 240);
  };

  if (phase === "hidden" || phase === "gone") return null;

  const multiSel = answers.industry || [];

  return (
    <>
      <style>{surveyStyles}</style>
      <div className="sv-backdrop" data-in={shown} data-out={leaving}
           role="dialog" aria-modal="true" aria-label="Visitor questions">
        <div className="sv-card">
          {phase === "thanks" ? (
            <ThanksPanel />
          ) : (
            <>
              <div className="sv-head">
                <span className="sv-brand"><span className="dot"></span> Megalis</span>
                <button className="sv-skip" type="button" onClick={skip}>Skip ✕</button>
              </div>
              <div className="sv-body">
                <p className="sv-intro">Just 3 quick questions to help us know you better!</p>
                <div className="sv-steps">
                  {SURVEY_QUESTIONS.map((q, i) => (
                    <div key={q.id} className="sv-step"
                         data-state={i === step ? "current" : i < step ? "past" : "next"}
                         aria-hidden={i !== step}>
                      <div>
                        <div className="sv-qnum">Q{i + 1} / {SURVEY_QUESTIONS.length}</div>
                        <h3 className="sv-q">{q.q}</h3>
                        {q.multi ? <div className="sv-hint sv-subhint">Multiple answers possible</div> : null}
                      </div>
                      <div className="sv-opts">
                        {q.options.map((o) => (
                          <button key={o} className="sv-opt" type="button"
                                  tabIndex={i === step ? 0 : -1}
                                  data-sel={q.multi ? multiSel.includes(o) : answers[q.id] === o}
                                  onClick={() => answer(i, o)}>
                            {o}
                          </button>
                        ))}
                      </div>
                      {q.multi && multiSel.includes("Other") ? (
                        <input className="sv-other" type="text"
                               value={otherText}
                               tabIndex={i === step ? 0 : -1}
                               placeholder="Tell us which industry (optional)"
                               aria-label="Your industry"
                               onChange={(e) => setOtherText(e.target.value)} />
                      ) : null}
                      {q.multi ? (
                        <div className="sv-foot">
                          <span className="sv-hint"></span>
                          <div className="sv-nav">
                            <button className="sv-back" type="button"
                                    tabIndex={i === step ? 0 : -1}
                                    disabled={i === 0}
                                    onClick={() => setStep(i - 1)}>
                              ← Back
                            </button>
                            <button className="sv-next" type="button"
                                    tabIndex={i === step ? 0 : -1}
                                    disabled={multiSel.length === 0}
                                    onClick={() => finish({ ...answers, industry: multiSel, industryOther: otherText.trim() || undefined })}>
                              Done →
                            </button>
                          </div>
                        </div>
                      ) : (
                        <div className="sv-foot">
                          <span className="sv-hint">Select one</span>
                          <div className="sv-nav">
                            <button className="sv-back" type="button"
                                    tabIndex={i === step ? 0 : -1}
                                    disabled={i === 0}
                                    onClick={() => setStep(i - 1)}>
                              ← Back
                            </button>
                            <button className="sv-next" type="button"
                                    tabIndex={i === step ? 0 : -1}
                                    disabled={!answers[q.id]}
                                    onClick={() => setStep(i + 1)}>
                              Next →
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
              <div className="sv-prog" aria-hidden="true">
                {SURVEY_QUESTIONS.map((q, i) => <i key={q.id} data-on={i <= step}></i>)}
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
}

function ThanksPanel() {
  const [on, setOn] = React.useState(false);
  React.useEffect(() => { const id = requestAnimationFrame(() => setOn(true)); return () => cancelAnimationFrame(id); }, []);
  return (
    <div className="sv-thanks" data-in={on}>
      <span className="mark" aria-hidden="true"></span>
      <p>Welcome to MEGALIS!</p>
    </div>
  );
}

Object.assign(window, { Survey });

// Dev helper: run resetSurvey() in the console to see the popup again.
window.resetSurvey = () => {
  try { localStorage.removeItem("megalis:survey"); } catch (e) {}
  location.reload();
};
