// Top-level shell: mode toggle (Runner / Coach / Both) + Tweaks integration
const { useState: sUseState, useEffect: sUseEffect, useRef: sUseRef } = React;

// Default tweakable state
const RUN_TWEAKS_DEFAULTS = /*EDITMODE-BEGIN*/{
  "variation": "aurora",
  "accent": "#FF6B35",
  "showBoth": true,
  "iosScale": 0.78,
  "webScale": 0.66
}/*EDITMODE-END*/;

function ModeChip({ label, active, onClick, icon }) {
  return (
    <button onClick={onClick} style={{
      padding: "8px 14px", borderRadius: 999, display: "inline-flex", alignItems: "center", gap: 6,
      background: active ? "var(--ink)" : "transparent",
      color: active ? "#fff" : "var(--ink-2)",
      fontSize: 12.5, fontWeight: 600, letterSpacing: 0.1,
      whiteSpace: "nowrap",
      transition: "all 0.15s ease",
    }}>
      {icon} {label}
    </button>
  );
}

function TopBar({ mode, setMode }) {
  return (
    <div style={{
      position: "absolute", top: 14, left: "50%", transform: "translateX(-50%)",
      zIndex: 100, display: "flex", alignItems: "center", gap: 12,
    }}>
      <div className="glass" style={{
        display: "flex", alignItems: "center", padding: "6px 8px", borderRadius: 999, gap: 4,
      }}>
        <div style={{ padding: "0 8px 0 6px", display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{
            width: 24, height: 24, borderRadius: 7,
            background: "linear-gradient(135deg, #FF6B35, #FF3B30)",
            display: "flex", alignItems: "center", justifyContent: "center",
            boxShadow: "0 2px 6px rgba(255,107,53,0.3), inset 0 1px 0 rgba(255,255,255,0.3)",
          }}>
            <div style={{ width: 10, height: 10, borderRadius: 5, border: "2px solid white", borderRightColor: "transparent", transform: "rotate(-45deg)" }} />
          </div>
          <span style={{ fontSize: 13, fontWeight: 700, letterSpacing: -0.3 }}>Run</span>
        </div>
        <div style={{ width: 1, height: 18, background: "var(--line)" }} />
        <ModeChip label="Both" active={mode === "both"} onClick={() => setMode("both")} />
        <ModeChip label="Coach" active={mode === "coach"} onClick={() => setMode("coach")} />
        <ModeChip label="Athlete" active={mode === "athlete"} onClick={() => setMode("athlete")} />
      </div>
    </div>
  );
}

// Frosted Safari-style window chrome (lighter than the dark starter)
function SafariFrame({ url = "run.app/coach", children, width, height }) {
  return (
    <div style={{
      width, height, borderRadius: 16, overflow: "hidden",
      background: "rgba(255,252,245,0.85)",
      boxShadow: "0 40px 100px rgba(28,25,23,0.18), 0 8px 24px rgba(28,25,23,0.08), 0 0 0 0.5px rgba(28,25,23,0.1)",
      display: "flex", flexDirection: "column",
      backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)",
    }}>
      {/* title bar */}
      <div style={{
        height: 42, padding: "0 14px", flexShrink: 0,
        background: "rgba(250,245,238,0.7)", backdropFilter: "blur(20px)",
        WebkitBackdropFilter: "blur(20px)",
        borderBottom: "0.5px solid rgba(28,25,23,0.08)",
        display: "flex", alignItems: "center", gap: 12,
      }}>
        <div style={{ display: "flex", gap: 7 }}>
          <div style={{ width: 11, height: 11, borderRadius: "50%", background: "#FF5F57", boxShadow: "inset 0 0 0 0.5px rgba(0,0,0,0.1)" }} />
          <div style={{ width: 11, height: 11, borderRadius: "50%", background: "#FEBC2E", boxShadow: "inset 0 0 0 0.5px rgba(0,0,0,0.1)" }} />
          <div style={{ width: 11, height: 11, borderRadius: "50%", background: "#28C840", boxShadow: "inset 0 0 0 0.5px rgba(0,0,0,0.1)" }} />
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <Ic.ChevronLeft size={14} color="rgba(28,25,23,0.4)" />
          <Ic.Chevron size={14} color="rgba(28,25,23,0.25)" />
        </div>
        <div style={{
          flex: 1, height: 26, borderRadius: 7,
          background: "rgba(28,25,23,0.05)",
          display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
          fontSize: 12, color: "var(--ink-2)", maxWidth: 360, margin: "0 auto",
        }}>
          <Ic.Lock size={11} color="var(--ink-3)" />
          <span style={{ fontWeight: 500 }}>{url}</span>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <div style={{ width: 16, height: 16, borderRadius: 4, background: "rgba(28,25,23,0.06)" }} />
          <div style={{ width: 16, height: 16, borderRadius: 4, background: "rgba(28,25,23,0.06)" }} />
        </div>
      </div>
      <div style={{ flex: 1, overflow: "hidden", display: "flex" }}>
        {children}
      </div>
    </div>
  );
}

// Computes a scale to fit a frame of given size in a container
function useFitScale(containerRef, frameW, frameH, padding = 60) {
  const [scale, setScale] = sUseState(0.7);
  sUseEffect(() => {
    function compute() {
      const el = containerRef.current;
      if (!el) return;
      const r = el.getBoundingClientRect();
      const sw = (r.width - padding * 2) / frameW;
      const sh = (r.height - padding * 2) / frameH;
      setScale(Math.min(sw, sh, 1));
    }
    compute();
    const ro = new ResizeObserver(compute);
    if (containerRef.current) ro.observe(containerRef.current);
    window.addEventListener("resize", compute);
    return () => { ro.disconnect(); window.removeEventListener("resize", compute); };
  }, [frameW, frameH, padding]);
  return scale;
}

function PhoneStage({ variant }) {
  const ref = sUseRef();
  const scale = useFitScale(ref, 402, 874, 40);
  return (
    <div ref={ref} style={{
      flex: "0 0 auto", width: 460, height: "100%",
      display: "flex", alignItems: "center", justifyContent: "center",
      position: "relative",
    }}>
      <div style={{ transform: `scale(${scale})`, transformOrigin: "center" }}>
        <IOSDevice width={402} height={874}>
          <RunnerApp variant={variant} />
        </IOSDevice>
      </div>
    </div>
  );
}

function WebStage({ variant }) {
  const ref = sUseRef();
  // Coach dashboard ideal width × height
  const W = 1440, H = 900;
  const scale = useFitScale(ref, W, H, 40);
  return (
    <div ref={ref} style={{
      flex: 1, height: "100%", minWidth: 0,
      display: "flex", alignItems: "center", justifyContent: "center",
      position: "relative",
    }}>
      <div style={{ transform: `scale(${scale})`, transformOrigin: "center" }}>
        <SafariFrame url="run.app/coach/roster" width={W} height={H}>
          <CoachApp variant={variant} />
        </SafariFrame>
      </div>
    </div>
  );
}

// Aurora-y background for stage area
function StageBg({ variant }) {
  return (
    <div style={{
      position: "absolute", inset: 0, overflow: "hidden", zIndex: 0,
      background: variant === "pure"
        ? "linear-gradient(180deg, #F5EFE3 0%, #ECDDC1 100%)"
        : "linear-gradient(160deg, #FFE7CF 0%, #F4E8D5 40%, #ECD2A8 100%)",
    }}>
      {variant !== "pure" && (
        <>
          <div style={{
            position: "absolute", top: -200, left: -200, width: 800, height: 800,
            borderRadius: "50%", filter: "blur(140px)", opacity: 0.55,
            background: "radial-gradient(circle, #FFAB6B, transparent 65%)",
          }} />
          <div style={{
            position: "absolute", bottom: -300, right: -200, width: 900, height: 900,
            borderRadius: "50%", filter: "blur(140px)", opacity: 0.45,
            background: "radial-gradient(circle, #FF6B35, transparent 65%)",
          }} />
          <div style={{
            position: "absolute", top: "30%", right: "30%", width: 500, height: 500,
            borderRadius: "50%", filter: "blur(120px)", opacity: 0.35,
            background: "radial-gradient(circle, #FFCB6B, transparent 65%)",
          }} />
        </>
      )}
    </div>
  );
}

// ────────────── App root ──────────────
function App() {
  const [mode, setMode] = sUseState("both");
  const [t, setTweak] = useTweaks(RUN_TWEAKS_DEFAULTS);

  // Apply accent color live to CSS variables
  sUseEffect(() => {
    document.documentElement.style.setProperty("--accent", t.accent);
  }, [t.accent]);

  return (
    <div style={{ position: "relative", width: "100vw", height: "100vh", overflow: "hidden" }}>
      <StageBg variant={t.variation} />
      <TopBar mode={mode} setMode={setMode} />
      <TweaksPanel title="Tweaks">
        <TweakSection label="Variation">
          <TweakRadio
            value={t.variation}
            onChange={v => setTweak("variation", v)}
            options={[
              { value: "aurora", label: "Aurora" },
              { value: "pure", label: "Pure" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Accent color">
          <TweakColor
            value={t.accent}
            onChange={v => setTweak("accent", v)}
            options={["#FF6B35", "#FFB627", "#FF3B30", "#0A84FF", "#30D158"]}
          />
        </TweakSection>
      </TweaksPanel>

      <div style={{
        position: "relative", zIndex: 1, width: "100%", height: "100%",
        display: "flex", paddingTop: 70, paddingBottom: 30,
      }}>
        {mode === "both" && (
          <>
            <WebStage variant={t.variation} />
            <PhoneStage variant={t.variation} />
          </>
        )}
        {mode === "coach" && <WebStage variant={t.variation} />}
        {mode === "athlete" && (
          <div style={{ flex: 1, height: "100%", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <PhoneStage variant={t.variation} />
          </div>
        )}
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
