// ──────────────────────────────────────────────────────────────────
// Interactive prototype shell — wires individual screens together
// into a tap-thru flow. Also holds the Module-color usage spec
// artboard.
// ──────────────────────────────────────────────────────────────────

// Global preferences (theme + CTA tone) — pulled from Tweaks via window.
// Each Phone gets its own dark/light prop, so this is just a default.

// ── Interactive Auth / Onboarding prototype ─────────────────────
const AuthFlowPrototype = ({ dark = true }) => {
  const [stage, setStage] = React.useState("welcome");
  const [step, setStep] = React.useState(0);

  return (
    <Phone dark={dark}>
      {stage === "welcome" && (
        <WelcomeScreen onStart={() => setStage("signup")} onSignIn={() => setStage("login")} />
      )}
      {stage === "login" && (
        <LoginScreen
          onBack={() => setStage("welcome")}
          onLogin={() => { setStage("onboarding"); setStep(0); }}
          onSignup={() => setStage("signup")}
        />
      )}
      {stage === "signup" && (
        <SignUpOptionsScreen
          onBack={() => setStage("welcome")}
          onEmail={() => { setStage("onboarding"); setStep(0); }}
          onSignIn={() => setStage("login")}
        />
      )}
      {stage === "onboarding" && (
        <OnboardingScreen
          step={step}
          onNext={() => {
            if (step < ONBOARDING_STEPS.length - 1) setStep(step + 1);
            else setStage("role");
          }}
          onBack={() => setStep(Math.max(0, step - 1))}
          onSkip={() => setStage("role")}
        />
      )}
      {stage === "role" && (
        <RoleSelectionScreen onBack={() => setStage("onboarding")} onContinue={() => setStage("welcome")} />
      )}
    </Phone>
  );
};

// ── Interactive Builder Canvas prototype ─────────────────────────
const BuilderFlowPrototype = ({ dark = true }) => {
  const [stage, setStage] = React.useState("gallery");
  return (
    <Phone dark={dark}>
      {stage === "gallery" && (
        <BuilderGalleryScreen onOpenCanvas={() => setStage("intent")} onOpenSaved={() => setStage("saved")} />
      )}
      {stage === "intent" && (
        <DesignIntentScreen
          onClose={() => setStage("gallery")}
          onContinue={() => setStage("canvas")}
          onSkip={() => setStage("canvas")}
        />
      )}
      {stage === "canvas" && (
        <BuilderCanvasScreen onBack={() => setStage("intent")} onReview={() => setStage("review")} />
      )}
      {stage === "review" && (
        <BuilderReviewScreen onBack={() => setStage("canvas")} onSubmit={() => setStage("gallery")} />
      )}
      {stage === "saved" && (
        <EmptySavedDesigns onAction={() => setStage("intent")} />
      )}
    </Phone>
  );
};

// ── Interactive Profile + Settings prototype (Theme toggle works) ─
const ProfileFlowPrototype = ({ initialMode = "dark", initialCta = "mono", onModeChange, onCtaChange }) => {
  const [stage, setStage] = React.useState("profile");
  const [mode, setMode] = React.useState(initialMode);
  const [cta, setCta] = React.useState(initialCta);
  const dark = mode === "dark" || (mode === "system" && true);
  return (
    <Phone dark={dark}>
      {stage === "profile" && (
        <ProfileScreen onSettings={() => setStage("settings")} />
      )}
      {stage === "settings" && (
        <AccountSettingsScreen
          onBack={() => setStage("profile")}
          themeMode={mode}
          setThemeMode={(m) => { setMode(m); onModeChange && onModeChange(m); }}
          ctaTone={cta}
          setCtaTone={(c) => { setCta(c); onCtaChange && onCtaChange(c); }}
        />
      )}
    </Phone>
  );
};

// ── Module color usage spec ──────────────────────────────────────
// A single tall artboard showing where each of the 5 tints appears,
// with rules.
const ModuleColorSpec = () => {
  const modules = [
    { k: "athlete", title: "ATHLETE", body: "Your record, feed, status strip. The mat presence.", uses: ["Tab indicator", "Record stripe", "Feed signal"] },
    { k: "builder", title: "DESIGNER", body: "Drafts, builds, canvas mode. The custom-apparel surface. Lives under the Gear tab.", uses: ["Section accent", "Draft stripe", "Canvas alerts"] },
    { k: "store",   title: "GEAR",   body: "Orders, sponsor drops, fabric updates. Hosts the Designer.",          uses: ["Tab indicator", "Order stripe", "Drop badges"] },
    { k: "scout",   title: "SCOUT",   body: "Invitations, talent flags, recruiter touches.",   uses: ["DM stripe", "Inquiry badges", "Roster flags"] },
    { k: "dojo",    title: "DOJO",    body: "Gym, mat events, coach posts, open mat.",          uses: ["Gym feed stripe", "Event badges", "RSVP markers"] },
  ];
  return (
    <div className="tkdn tkdn-dark" style={{ width: 720, background: "var(--bg-primary)", color: "var(--text-primary)", padding: 32, borderRadius: 8 }}>
      <Overline style={{ color: "var(--accent)" }}>MODULE COLOR USAGE · SPEC</Overline>
      <div className="t-h2" style={{ marginTop: 8, marginBottom: 8 }}>5 tints. Navigation only.</div>
      <p className="t-body-lg" style={{ color: "var(--text-secondary)", maxWidth: 540 }}>
        Module tints are navigational markers - they identify which module a surface belongs to. They appear as edge stripes, dots, and tab indicators. They <strong>never</strong> fill buttons or backgrounds; the only fill color the brand has is orange-red.
      </p>

      <div style={{ marginTop: 32, display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 8 }}>
        {modules.map((m) => (
          <div key={m.k} style={{ border: "1px solid var(--border-subtle)", padding: 14, borderRadius: "var(--r-sm)" }}>
            <div style={{ height: 4, background: MODULE_TINTS[m.k], marginBottom: 14 }} />
            <Overline style={{ color: MODULE_TINTS[m.k] }}>{m.title}</Overline>
            <div className="t-caption-lg" style={{ marginTop: 6, color: "var(--text-secondary)", lineHeight: 1.5 }}>{m.body}</div>
            <Hairline style={{ margin: "12px 0" }} />
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 6 }}>
              {m.uses.map((u, i) => (
                <li key={i} className="t-caption-lg" style={{ color: "var(--text-tertiary)" }}>
                  <span style={{ display: "inline-block", width: 4, height: 4, background: MODULE_TINTS[m.k], marginRight: 6, verticalAlign: "middle" }} />
                  {u}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 32 }}>
        <Overline style={{ color: "var(--text-secondary)" }}>EXAMPLES · IN-CONTEXT</Overline>
      </div>
      <div style={{ marginTop: 16, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
        {/* Tab indicator */}
        <div style={{ padding: 16, border: "1px solid var(--border-subtle)", borderRadius: "var(--r-sm)" }}>
          <Overline style={{ color: "var(--text-tertiary)" }}>USAGE · TAB INDICATOR</Overline>
          <div style={{ marginTop: 14, height: 60, background: "var(--bg-primary)", border: "1px solid var(--border-subtle)", borderRadius: "var(--r-sm)", display: "flex", position: "relative" }}>
            {["athlete", "builder", "store", "dojo"].map((m, i) => (
              <div key={m} style={{ flex: 1, position: "relative", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", color: i === 0 ? "var(--text-primary)" : "var(--text-tertiary)" }}>
                <div style={{ position: "absolute", top: 0, left: "30%", right: "30%", height: 2, background: i === 0 ? MODULE_TINTS[m] : "transparent" }} />
                <div style={{ width: 16, height: 16, border: "1.5px solid currentColor" }} />
              </div>
            ))}
          </div>
          <p className="t-caption-lg" style={{ color: "var(--text-tertiary)", marginTop: 10 }}>2-px top rule, only on the active tab.</p>
        </div>

        {/* Edge stripe */}
        <div style={{ padding: 16, border: "1px solid var(--border-subtle)", borderRadius: "var(--r-sm)" }}>
          <Overline style={{ color: "var(--text-tertiary)" }}>USAGE · EDGE STRIPE</Overline>
          <div style={{ marginTop: 14, padding: 14, borderLeft: `3px solid ${MODULE_TINTS.dojo}`, background: "var(--bg-primary)" }}>
            <Overline style={{ color: "var(--text-tertiary)" }}>GYM · CITY BJJ</Overline>
            <div className="t-body-bold" style={{ marginTop: 4 }}>Open mat tonight 7pm</div>
          </div>
          <p className="t-caption-lg" style={{ color: "var(--text-tertiary)", marginTop: 10 }}>3-px left edge on feed cards.</p>
        </div>

        {/* Status dot */}
        <div style={{ padding: 16, border: "1px solid var(--border-subtle)", borderRadius: "var(--r-sm)" }}>
          <Overline style={{ color: "var(--text-tertiary)" }}>USAGE · STATUS DOT</Overline>
          <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
            {[
              { k: "athlete", t: "Mat presence" },
              { k: "builder", t: "Design saved" },
              { k: "scout", t: "New inquiry" },
            ].map((r) => (
              <div key={r.k} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ width: 8, height: 8, background: MODULE_TINTS[r.k], borderRadius: 99 }} />
                <span className="t-body">{r.t}</span>
              </div>
            ))}
          </div>
          <p className="t-caption-lg" style={{ color: "var(--text-tertiary)", marginTop: 10 }}>8-px dot on status lists.</p>
        </div>
      </div>

      <div style={{ marginTop: 32, padding: 16, border: "1px dashed var(--error)", borderRadius: "var(--r-sm)" }}>
        <Overline style={{ color: "var(--error)" }}>ANTI-PATTERN · DON'T</Overline>
        <div className="t-body" style={{ marginTop: 8, color: "var(--text-secondary)" }}>
          Don't fill buttons, badges, or surface backgrounds with module tints. They aren't accents - they're navigational signals. The only fill in the brand is brand-red.
        </div>
      </div>
    </div>
  );
};

// ── System reference card (tokens at a glance) ───────────────────
const SystemReferenceCard = () => (
  <div className="tkdn tkdn-dark" style={{ width: 720, background: "var(--bg-primary)", color: "var(--text-primary)", padding: 32, borderRadius: 8 }}>
    <Overline style={{ color: "var(--accent)" }}>SYSTEM · REFERENCE</Overline>
    <div className="t-h2" style={{ marginTop: 8 }}>Tokens at a glance.</div>

    <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
      {/* Color */}
      <div>
        <Overline style={{ color: "var(--text-secondary)" }}>COLOR · DARK MODE</Overline>
        <div style={{ marginTop: 12, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
          {[
            ["#0D0808", "BG"],
            ["#FFFFFF", "TEXT"],
            ["#C61D1D", "ACCENT"],
            ["#595959", "MUTED"],
          ].map(([c, l]) => (
            <div key={l}>
              <div style={{ aspectRatio: 1, background: c, border: "1px solid var(--border-subtle)", borderRadius: 4 }} />
              <Overline style={{ marginTop: 6, color: "var(--text-tertiary)" }}>{l}</Overline>
              <div className="t-caption" style={{ color: "var(--text-tertiary)" }}>{c}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Type */}
      <div>
        <Overline style={{ color: "var(--text-secondary)" }}>TYPE · FIGTREE</Overline>
        <div style={{ marginTop: 12 }}>
          <div className="t-h1">Aa</div>
          <Overline style={{ color: "var(--text-tertiary)", marginTop: 6 }}>H1 · 45/49 · 700 · +0.03em</Overline>
        </div>
        <Hairline style={{ margin: "12px 0" }} />
        <div className="t-h4">The card is set.</div>
        <Overline style={{ color: "var(--text-tertiary)", marginTop: 4 }}>H4 · 28/32 · 700 · +0.01em</Overline>
        <Hairline style={{ margin: "12px 0" }} />
        <div className="t-body">Body sentence in Figtree 400, 14/20.</div>
      </div>

      {/* Radius */}
      <div>
        <Overline style={{ color: "var(--text-secondary)" }}>RADIUS · BINARY</Overline>
        <div style={{ marginTop: 12, display: "flex", gap: 12, alignItems: "flex-end" }}>
          <div>
            <div style={{ width: 60, height: 60, border: "1px solid var(--border-default)", borderRadius: 3 }} />
            <Overline style={{ color: "var(--text-tertiary)", marginTop: 6 }}>3 · XS</Overline>
          </div>
          <div>
            <div style={{ width: 60, height: 60, border: "1px solid var(--border-default)", borderRadius: 8 }} />
            <Overline style={{ color: "var(--text-tertiary)", marginTop: 6 }}>8 · SM</Overline>
          </div>
          <div>
            <div style={{ width: 80, height: 40, border: "1px solid var(--border-default)", borderRadius: 120 }} />
            <Overline style={{ color: "var(--text-tertiary)", marginTop: 6 }}>120 · PILL</Overline>
          </div>
          <div>
            <div style={{ width: 40, height: 40, border: "1px solid var(--border-default)", borderRadius: 99 }} />
            <Overline style={{ color: "var(--text-tertiary)", marginTop: 6 }}>9999 · FULL</Overline>
          </div>
        </div>
      </div>

      {/* Spacing */}
      <div>
        <Overline style={{ color: "var(--text-secondary)" }}>SPACING · 8-PT GRID</Overline>
        <div style={{ marginTop: 12 }}>
          {[4, 8, 12, 16, 24, 32, 48].map((s) => (
            <div key={s} style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 6 }}>
              <div style={{ width: s * 2, height: 6, background: "var(--accent)" }} />
              <span className="t-caption-lg" style={{ color: "var(--text-tertiary)" }}>{s}px</span>
            </div>
          ))}
        </div>
      </div>
    </div>

    <Hairline style={{ margin: "24px 0" }} />

    <Overline style={{ color: "var(--text-secondary)" }}>BUTTON · STATES</Overline>
    <div style={{ marginTop: 12, display: "flex", gap: 10, flexWrap: "wrap" }}>
      <Button label="MONO · PRIMARY" tone="mono" size="medium" />
      <Button label="MONO · SECONDARY" tone="mono" variant="secondary" size="medium" />
      <Button label="ACCENT · PRIMARY" tone="accent" size="medium" />
      <Button label="ACCENT · SECONDARY" tone="accent" variant="secondary" size="medium" />
      <Button label="GHOST" variant="ghost" tone="mono" size="medium" />
      <Button label="DESTRUCTIVE" variant="destructive" size="medium" />
    </div>
  </div>
);

// ── Notes card (rationale) ───────────────────────────────────────
const NotesCard = ({ title, children }) => (
  <div style={{
    width: 360, padding: 24, background: "#fef4a8", color: "#5a4a2a",
    fontFamily: "Figtree, sans-serif", borderRadius: 8,
    boxShadow: "0 4px 16px rgba(0,0,0,0.05)",
  }}>
    <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 12, opacity: 0.7 }}>NOTE</div>
    <div style={{ fontSize: 18, fontWeight: 700, lineHeight: 1.25, marginBottom: 12 }}>{title}</div>
    <div style={{ fontSize: 13, lineHeight: 1.55 }}>{children}</div>
  </div>
);

Object.assign(window, {
  AuthFlowPrototype,
  BuilderFlowPrototype,
  ProfileFlowPrototype,
  ModuleColorSpec,
  SystemReferenceCard,
  NotesCard,
});
