// mobilehome.jsx — the mobile homepage. Instead of the long scrolling marketing
// page, mobile gets a native-app feel: full-screen, swipeable "screens" with
// pagination dots and a persistent bottom action bar. Desktop is untouched.
// (All top-level names are unique across the shared global scope — *MH suffix.)
const { useState: useStateMH, useEffect: useEffectMH, useRef: useRefMH } = React;

// Entrance for a carousel element: it rises + fades into place when its screen
// becomes active, and re-plays every time you land on that screen (first load
// included). `none` when inactive so the off-screen element just rests visible.
const mhRise = (active, delay = 0) => ({ animation: active ? `mh-rise .6s cubic-bezier(.16,1,.3,1) ${delay}s both` : "none" });

/* Small presentational bits, kept local so the screens read cleanly. */
function MHPhoneCard({ children, style }) {
  // A soft "device panel" that the visuals sit inside — gives each screen a
  // tangible, product-like centrepiece.
  return (
    <div style={{
      width: "100%", maxWidth: 320, marginInline: "auto", borderRadius: 26, padding: 16,
      background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-xl)",
      ...style,
    }}>{children}</div>
  );
}

/* ---- the four screens ---- */
function MHScreenIntro({ active }) {
  const cards = [
    { cat: "vehicle", name: "Land Cruiser", amount: "₦92M", status: "insured", rot: -6, y: 0 },
    { cat: "property", name: "Family Home", amount: "₦350M", status: "partial", rot: 2, y: 74 },
    { cat: "jewelry", name: "Rolex Submariner", amount: "₦41M", status: "uninsured", rot: -3, y: 148 },
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: 22 }}>
      <div style={{ position: "relative", width: "100%", maxWidth: 320, height: 232 }}>
        {cards.map((c, i) => (
          <div key={c.name} style={{
            position: "absolute", left: "50%", top: c.y, width: "100%", maxWidth: 300,
            // mh-card-stack (styles.css) is a two-phase entrance: the cards fall
            // from above and land STACKED on each other (all at top:0 via
            // --mh-stack), then break apart and push down into their fanned
            // resting slots (--mh-rot). --mh-drop is the above-viewport start.
            "--mh-rot": `${c.rot}deg`,
            "--mh-drop": `${-(c.y + 170)}px`,
            "--mh-stack": `${-c.y}px`,
            // Resting transform (used when the screen is off-screen / reduced motion).
            transform: `translateX(-50%) rotate(${c.rot}deg)`,
            animation: active ? `mh-card-stack 1.15s cubic-bezier(.26,1,.4,1) ${i * 0.12}s both` : "none",
            zIndex: i + 1,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11, padding: 12, borderRadius: 16, background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-lg)" }}>
              <window.AssetThumb category={c.cat} size={40} />
              <div style={{ flex: 1, minWidth: 0, textAlign: "left" }}>
                <div style={{ fontWeight: 700, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</div>
                <div className="mono" style={{ fontSize: 11.5, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{c.amount}</div>
              </div>
              <window.StatusBadge status={c.status} size="sm" />
            </div>
          </div>
        ))}
      </div>
      <div>
        <h1 className="display" style={{ fontSize: 33, lineHeight: 1.06, letterSpacing: "-0.03em", margin: 0, ...mhRise(active, 0.34) }}>
          Your assets, vaulted<br />&amp; <span className="vc-grad-text">covered.</span>
        </h1>
        <p style={{ fontSize: 15, color: "var(--text-muted)", lineHeight: 1.5, margin: "14px auto 0", maxWidth: 300, ...mhRise(active, 0.44) }}>
          One vault for everything you own, with the cover, all in one place.
        </p>
      </div>
    </div>
  );
}

function MHScreenCova({ active }) {
  const lines = [
    { role: "user", text: "I just bought a Hilux for ₦52M" },
    { role: "bot", text: "Added to VaultLog ✓. Risk scored 58/100. Want matched quotes?" },
  ];
  const [n, setN] = useStateMH(0);
  useEffectMH(() => {
    if (!active) { setN(0); return; }
    if (n >= lines.length) return;
    const t = setTimeout(() => setN((x) => x + 1), n === 0 ? 450 : 1100);
    return () => clearTimeout(t);
  }, [active, n]);
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: 24 }}>
      <MHPhoneCard>
        <div style={{ display: "flex", alignItems: "center", gap: 9, paddingBottom: 12, marginBottom: 10, borderBottom: "1px solid var(--border)" }}>
          <span style={{ display: "grid", placeItems: "center", width: 28, height: 28, borderRadius: 999, background: "linear-gradient(135deg,var(--accent-2),var(--accent))", color: "#fff" }}><window.Icon name="sparkle" size={15} /></span>
          <div style={{ fontWeight: 700, fontSize: 13.5 }}>Cova</div>
          <span style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 5, fontSize: 10.5, color: "var(--success)", fontWeight: 600 }}><span style={{ width: 6, height: 6, borderRadius: 9, background: "var(--success)" }} />Online</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8, minHeight: 132 }}>
          {lines.slice(0, n).map((l, i) => (
            <div key={i} style={{ alignSelf: l.role === "user" ? "flex-end" : "flex-start", maxWidth: "88%", animation: "vc-fade-up .4s var(--ease) both" }}>
              <div style={{ padding: "9px 12px", borderRadius: l.role === "user" ? "13px 13px 3px 13px" : "3px 13px 13px 13px", fontSize: 12.5, lineHeight: 1.4, textAlign: "left", background: l.role === "user" ? "var(--accent)" : "var(--surface-2)", color: l.role === "user" ? "#fff" : "var(--text)", border: l.role === "user" ? "none" : "1px solid var(--border)" }}>{l.text}</div>
            </div>
          ))}
          {n < lines.length && <div style={{ alignSelf: lines[n]?.role === "user" ? "flex-end" : "flex-start" }}><div style={{ display: "flex", gap: 4, padding: "9px 13px", background: "var(--surface-2)", borderRadius: 13, border: "1px solid var(--border)" }}>{[0, 1, 2].map((i) => <span key={i} style={{ width: 5, height: 5, borderRadius: 9, background: "var(--text-faint)", animation: `vc-dot 1.2s ${i * 0.15}s infinite` }} />)}</div></div>}
        </div>
      </MHPhoneCard>
      <div>
        <h2 className="display" style={{ fontSize: 27, lineHeight: 1.1, letterSpacing: "-0.02em", margin: 0 }}>Just say what you own.</h2>
        <p style={{ fontSize: 15, color: "var(--text-muted)", lineHeight: 1.5, margin: "12px auto 0", maxWidth: 300 }}>
          Cova logs it, values it and scores the risk, in plain words, in seconds.
        </p>
      </div>
    </div>
  );
}

function MHScreenInsure({ active }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: 24 }}>
      <MHPhoneCard style={{ paddingBlock: 26, overflow: "hidden", ...mhRise(active, 0) }}>
        <div style={{ position: "relative", display: "grid", placeItems: "center", height: 132 }}>
          <span style={{ position: "absolute", top: -8, right: 0, padding: "5px 12px", borderRadius: 999, background: "var(--success)", color: "#fff", fontSize: 12.5, fontWeight: 800, boxShadow: "var(--shadow-md)", zIndex: 3, opacity: active ? 1 : 0, transform: active ? "none" : "scale(.7)", transition: "all .5s var(--ease) .5s" }}>save ~18%</span>
          {/* Plant pops up first in the centre; Fleet & Store then break apart
              and push out to the sides (mh-chip-push). Base transform holds the
              spread position for reduced-motion / off-screen. */}
          <div style={{ position: "absolute", marginTop: 22, "--mh-x": "-82px", "--mh-r": "-8deg", transform: "translateX(var(--mh-x)) rotate(var(--mh-r))", animation: active ? "mh-chip-push .8s cubic-bezier(.3,1.35,.4,1) .18s both" : "none" }}><MHMiniChip cat="vehicle" label="Fleet" /></div>
          <div style={{ position: "absolute", marginTop: 22, "--mh-x": "82px", "--mh-r": "8deg", transform: "translateX(var(--mh-x)) rotate(var(--mh-r))", animation: active ? "mh-chip-push .8s cubic-bezier(.3,1.35,.4,1) .18s both" : "none" }}><MHMiniChip cat="property" label="Store" /></div>
          <div style={{ position: "absolute", marginTop: 22, zIndex: 2, animation: active ? "mh-chip-push .5s cubic-bezier(.2,1,.4,1) 0s both" : "none" }}><MHMiniChip cat="equipment" label="Plant" /></div>
        </div>
      </MHPhoneCard>
      <div>
        <h2 className="display" style={{ fontSize: 27, lineHeight: 1.1, letterSpacing: "-0.02em", margin: 0, ...mhRise(active, 0.32) }}>Insure it your way.</h2>
        <p style={{ fontSize: 15, color: "var(--text-muted)", lineHeight: 1.5, margin: "12px auto 0", maxWidth: 300, ...mhRise(active, 0.42) }}>
          Cover one thing, or bundle assets into a single policy and cut the premium.
        </p>
      </div>
    </div>
  );
}
function MHMiniChip({ cat, label }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 7, padding: "8px 12px", borderRadius: 12, background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-md)", whiteSpace: "nowrap" }}>
      <window.AssetThumb category={cat} size={24} radius={7} />
      <span style={{ fontWeight: 700, fontSize: 12 }}>{label}</span>
    </div>
  );
}

/* ---- the swipeable shell ----
   VaultCova is chat-first, so the Cova composer is PINNED at the bottom of every
   screen: the swipeable screens are a showcase, but the primary action — the one
   thing always in reach — is talking to Cova. Type from screen 1 and you're in. */
function MobileHome({ onStart, onLogin, onToggleTheme, isDark, logoV = "vault" }) {
  const screens = ["intro", "cova", "insure"];
  const [i, setI] = useStateMH(0);
  const [drag, setDrag] = useStateMH(0); // live finger offset in px
  const [msg, setMsg] = useStateMH("");
  const [listening, setListening] = useStateMH(false);
  const [auto, setAuto] = useStateMH(true); // auto-advance until the user engages
  const [instant, setInstant] = useStateMH(false); // wrap without a backward slide
  const startX = useRefMH(0);
  const dragging = useRefMH(false);
  const wRef = useRefMH(null);
  const iRef = useRefMH(0);         // current index, readable inside the interval
  const resumeT = useRefMH(null);
  const rotating = window.useRotatingPh ? window.useRotatingPh(!listening) : "Tell Cova what you own…";
  const ph = listening ? "Listening… speak now" : rotating;
  const locale = window.I18N ? window.I18N.localeFor((window.useT && window.useT().lang) || "en") : "en-NG";

  const clamp = (n) => Math.max(0, Math.min(screens.length - 1, n));
  const goTo = (n) => setI(clamp(n));

  // Auto-swipe: cycle the showcase screens forward and wrap round (1 -> 2 -> 3 ->
  // 1 -> …), never running backward. The last -> first hop resets instantly (no
  // reverse slide) while the intro's cards drop back in, so it reads as a clean
  // loop. Pauses the moment the user takes over — swipes, taps a dot, or focuses
  // the composer — and resumes after a spell of inactivity. Honours reduced-motion.
  useEffectMH(() => { iRef.current = i; }, [i]);
  const pauseAuto = () => { setAuto(false); if (resumeT.current) clearTimeout(resumeT.current); };
  const scheduleResume = () => { if (resumeT.current) clearTimeout(resumeT.current); resumeT.current = setTimeout(() => setAuto(true), 7000); };
  useEffectMH(() => {
    if (!auto) return;
    if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const id = setInterval(() => {
      const next = iRef.current + 1;
      if (next >= screens.length) { setInstant(true); setI(0); }  // wrap: cut, don't rewind
      else setI(next);
    }, 4200);
    return () => clearInterval(id);
  }, [auto]);
  // After the wrapped (transition-less) frame paints, re-enable the slide so the
  // next 1 -> 2 move animates normally again.
  useEffectMH(() => {
    if (!instant) return;
    const r = requestAnimationFrame(() => requestAnimationFrame(() => setInstant(false)));
    return () => cancelAnimationFrame(r);
  }, [instant]);
  useEffectMH(() => () => { if (resumeT.current) clearTimeout(resumeT.current); }, []);

  const onDown = (x) => { dragging.current = true; startX.current = x; pauseAuto(); };
  const onMove = (x) => { if (dragging.current) setDrag(x - startX.current); };
  const onUp = () => {
    if (!dragging.current) return;
    dragging.current = false;
    const w = wRef.current ? wRef.current.offsetWidth : 320;
    const threshold = Math.min(70, w * 0.18);
    if (drag < -threshold) goTo(i + 1);
    else if (drag > threshold) goTo(i - 1);
    setDrag(0);
    scheduleResume();
  };

  const submit = (e) => { e.preventDefault(); onStart(msg.trim() || undefined); };

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--hero-grad)", overflow: "hidden" }}>
      {/* top bar — minimal, app-like */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 18px", flexShrink: 0 }}>
        <window.Logo variant={logoV} size={28} onClick={() => goTo(0)} />
        <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
          <button onClick={onToggleTheme} className="vc-focus" style={{ display: "grid", placeItems: "center", width: 38, height: 38, borderRadius: 999, color: "var(--text-muted)" }} aria-label="Toggle theme"><window.Icon name={isDark ? "sun" : "moon"} size={18} /></button>
          <window.Btn variant="ghost" size="sm" onClick={onLogin}>Log in</window.Btn>
        </div>
      </div>

      {/* swipe area (showcase) */}
      <div
        ref={wRef}
        style={{ flex: 1, position: "relative", overflow: "hidden", touchAction: "pan-y" }}
        onTouchStart={(e) => onDown(e.touches[0].clientX)}
        onTouchMove={(e) => onMove(e.touches[0].clientX)}
        onTouchEnd={onUp}
        onMouseDown={(e) => onDown(e.clientX)}
        onMouseMove={(e) => dragging.current && onMove(e.clientX)}
        onMouseUp={onUp}
        onMouseLeave={onUp}
      >
        <div style={{
          display: "flex", height: "100%",
          transform: `translateX(calc(${-i * 100}% + ${drag}px))`,
          transition: (dragging.current || instant) ? "none" : "transform .5s cubic-bezier(.22,1,.36,1)",
        }}>
          {screens.map((s, idx) => (
            <div key={s} style={{ flex: "0 0 100%", height: "100%", overflowY: "auto", display: "flex", alignItems: "center", justifyContent: "center", padding: "8px 26px 12px" }}>
              <div style={{ width: "100%", maxWidth: 380 }}>
                {s === "intro" && <MHScreenIntro active={i === idx} />}
                {s === "cova" && <MHScreenCova active={i === idx} />}
                {s === "insure" && <MHScreenInsure active={i === idx} />}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* dots */}
      <div style={{ display: "flex", gap: 7, alignItems: "center", justifyContent: "center", padding: "6px 0 12px", flexShrink: 0 }}>
        {screens.map((s, idx) => (
          <button key={s} onClick={() => { goTo(idx); pauseAuto(); scheduleResume(); }} aria-label={`Go to screen ${idx + 1}`} style={{
            height: 7, borderRadius: 999, border: "none", cursor: "pointer", padding: 0,
            width: idx === i ? 22 : 7,
            background: idx === i ? "var(--accent)" : "var(--border-strong)",
            transition: "all .35s var(--ease)",
          }} />
        ))}
      </div>

      {/* PINNED chat-first composer — the primary action on every screen */}
      <div style={{ flexShrink: 0, padding: "12px 22px calc(16px + env(safe-area-inset-bottom))", borderTop: "1px solid var(--border)", background: "var(--glass)", backdropFilter: "blur(16px)", WebkitBackdropFilter: "blur(16px)", display: "flex", flexDirection: "column", gap: 10, alignItems: "center" }}>
        <form onSubmit={submit} style={{ width: "100%", maxWidth: 380 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 8px 8px 16px", borderRadius: 999, background: "var(--surface)", border: "1.5px solid " + (listening ? "var(--accent)" : "var(--border)"), boxShadow: "var(--shadow-lg)", transition: "border-color .2s var(--ease)" }}>
            <window.Icon name="sparkle" size={19} style={{ color: "var(--accent)", flexShrink: 0 }} />
            <input value={msg} onChange={(e) => setMsg(e.target.value)} placeholder={ph} aria-label="Ask Cova"
              onFocus={pauseAuto} onBlur={scheduleResume}
              style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontSize: 15, color: "var(--text)", minWidth: 0 }} />
            {window.GuestClipBtn && <window.GuestClipBtn size={38} />}
            {window.VoiceMicButton && <window.VoiceMicButton locale={locale} onTranscript={setMsg} onListenChange={setListening} size={38} />}
            <window.Btn type="submit" iconR="arrowR" size="sm">{msg.trim() ? "Ask Cova" : "Start"}</window.Btn>
          </div>
        </form>
        <button onClick={() => onStart()} style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-faint)", padding: "2px 8px" }}>
          New here? <span style={{ color: "var(--accent)", fontWeight: 700 }}>Get started free</span>
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { MobileHome });
