/* =========================================================================
 *  Python Tutor — Brandmark + animated brandmark + splash screen
 *  -----------------------------------------------------------------------
 *  Mirrors the CTWCAD brandmark family in components/views-misc.jsx +
 *  primitives.jsx so the two sites feel like siblings:
 *
 *    PyBrand            — small static mark used in topbars
 *    AnimatedPyBrand    — choreographed draw-in (rounded rect → chevron
 *                         → underscore pop). Used on INITIALIZING /
 *                         SIGNED_OUT gate states and the splash.
 *    PythonSplashScreen — once-per-session full-screen brandmark
 *                         animation that fades to reveal the app.
 *
 *  Choreography mirrors AnimatedBrandmark:
 *    t=0.00  outer rounded square draws (2.0s, ease)
 *    t=1.45  chevron `>` draws         (1.0s, ease)
 *    t=2.55  underscore pops in        (0.7s, scaleX [0,1.5,1])
 *    →3.25s total. Splash holds 250 ms then fades 0.45s.
 *
 *  The outer rounded square uses an open path with an 8-unit overshoot
 *  past its starting point — same trick as ROUNDED_RECT_PATH in
 *  primitives.jsx — so framer-motion's pathLength animation doesn't
 *  leave a hair gap at the seam where the path closes.
 * =======================================================================*/

const PY_ROUNDED_RECT_PATH =
  "M 9 3 L 23 3 A 6 6 0 0 1 29 9 L 29 23 A 6 6 0 0 1 23 29 " +
  "L 9 29 A 6 6 0 0 1 3 23 L 3 9 A 6 6 0 0 1 9 3 L 17 3";
const PY_CHEVRON_PATH = "M 10 11 L 17 16 L 10 21";
// Underscore line endpoints; pop-in animates scaleX from the center
// of the line, so we use a proper <line> rather than a path.
const PY_UNDER_X1 = 19;
const PY_UNDER_X2 = 24;
const PY_UNDER_Y  = 22;
const PY_UNDER_CX = (PY_UNDER_X1 + PY_UNDER_X2) / 2; // 21.5

function PyBrand({ size = 22, withWord = true }) {
  /* Small static mark for topbars / inline use. Same colors and
     stroke widths as AnimatedPyBrand so animated → static doesn't
     visually shift. */
  return (
    <span className="pt-brand">
      <svg width={size} height={size} viewBox="0 0 32 32" aria-hidden="true">
        <rect x="3" y="3" width="26" height="26" rx="6"
              fill="none" stroke="var(--ct-fg)" strokeWidth="1.5"/>
        <path d={PY_CHEVRON_PATH}
              fill="none" stroke="var(--ct-accent)" strokeWidth="1.7"
              strokeLinecap="round" strokeLinejoin="round"/>
        <line x1={PY_UNDER_X1} y1={PY_UNDER_Y} x2={PY_UNDER_X2} y2={PY_UNDER_Y}
              stroke="var(--ct-accent)" strokeWidth="1.7" strokeLinecap="round"/>
      </svg>
      {withWord && <span className="ct-mono pt-brand-word">PYTHON&nbsp;TUTOR</span>}
    </span>
  );
}

function AnimatedPyBrand({ size = 120 }) {
  const M = window.FramerMotion ? window.FramerMotion.motion : null;
  if (!M) {
    // Framer Motion not loaded yet — fall back to the static mark so
    // we don't render a blank box.
    return <PyBrand size={size} withWord={false} />;
  }
  const ease = [0.22, 1, 0.36, 1];
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" aria-hidden="true">
      <M.path
        d={PY_ROUNDED_RECT_PATH}
        fill="none" stroke="currentColor" strokeWidth="1.5"
        strokeLinecap="round" strokeLinejoin="round"
        initial={{ pathLength: 0, opacity: 0 }}
        animate={{ pathLength: 1, opacity: 1 }}
        transition={{ duration: 2.0, ease }}
      />
      <M.path
        d={PY_CHEVRON_PATH}
        fill="none" stroke="var(--ct-accent)" strokeWidth="1.7"
        strokeLinecap="round" strokeLinejoin="round"
        initial={{ pathLength: 0 }}
        animate={{ pathLength: 1 }}
        transition={{ duration: 1.0, delay: 1.45, ease }}
      />
      <M.line
        x1={PY_UNDER_X1} y1={PY_UNDER_Y} x2={PY_UNDER_X2} y2={PY_UNDER_Y}
        stroke="var(--ct-accent)" strokeWidth="1.7" strokeLinecap="round"
        initial={{ scaleX: 0, opacity: 0 }}
        animate={{ scaleX: [0, 1.5, 1], opacity: 1 }}
        transition={{ duration: 0.7, delay: 2.55, ease }}
        style={{ transformOrigin: `${PY_UNDER_CX}px ${PY_UNDER_Y}px` }}
      />
    </svg>
  );
}

/* =========================================================================
 *  PythonSplashScreen — first-impression brandmark animation
 *  ---------------------------------------------------------------------
 *  Plays once per browser session: AnimatedPyBrand draws in, then the
 *  overlay fades out and reveals whatever the gate is showing behind.
 *  Skipped during the desktop OAuth handoff (?port= present) — those
 *  visitors are mid-task on a loopback POST and a 4-second splash is
 *  just friction.
 *
 *  Click anywhere on the splash to skip the rest of the animation.
 * =======================================================================*/
function PythonSplashScreen() {
  const M = window.FramerMotion ? window.FramerMotion.motion : null;
  const A = window.FramerMotion ? window.FramerMotion.AnimatePresence : null;
  // Skip during the desktop-signin handoff. The page itself shows
  // its own progress UI; we don't want a splash on top.
  const isDesktopHandoff = typeof window !== "undefined" &&
    (window.location.pathname === "/desktop-signin" ||
     new URLSearchParams(window.location.search).get("port") !== null);
  const [show, setShow] = React.useState(() => {
    if (isDesktopHandoff) return false;
    try { return sessionStorage.getItem("pythonTutor.splashShown") !== "1"; }
    catch { return false; }
  });

  React.useEffect(() => {
    if (!show) return;
    try { sessionStorage.setItem("pythonTutor.splashShown", "1"); } catch {}
    // 3.25s choreography + ~250ms hold + 0.45s fade out = 3.7s total.
    const t = setTimeout(() => setShow(false), 3700);
    return () => clearTimeout(t);
  }, [show]);

  if (!M || !A) return null;

  return (
    <A>
      {show && (
        <M.div
          className="pt-splash"
          initial={{ opacity: 1 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.45, ease: [0.22, 1, 0.36, 1] }}
          onClick={() => setShow(false)}
          role="presentation"
        >
          <div className="pt-splash-mark">
            <AnimatedPyBrand size={140} />
          </div>
          <div className="pt-splash-skip ct-mono ct-dim">click anywhere to skip</div>
        </M.div>
      )}
    </A>
  );
}

window.PyBrand = PyBrand;
window.AnimatedPyBrand = AnimatedPyBrand;
window.PythonSplashScreen = PythonSplashScreen;
