// ============================================================
// FitMinds — Login + Parent/Teacher Portal
// ============================================================

function LoginPage({ onLogin, brand }) {
  const [role, setRole] = React.useState("admin"); // admin | super | client
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [error, setError] = React.useState("");

  // prefill email per role so testers don't need to remember it; password stays empty
  React.useEffect(() => {
    const u = AUTH_USERS.find(u => u.role === role);
    if (u) { setEmail(u.email); setPw(""); setError(""); }
  }, [role]);

  const handleSubmit = (e) => {
    if (e) e.preventDefault();
    const user = AUTH_USERS.find(
      u => u.email.toLowerCase() === email.trim().toLowerCase() && u.password === pw
    );
    if (!user) { setError("Wrong email or password."); return; }
    setError("");
    onLogin(user);
  };

  return (
    <div className="login-root">
      <div className="login-art">
        <div>
          <div className="flex items-center gap-3">
            <BrandMark size={42} />
            <div style={{ fontSize: 18, fontWeight: 700 }}>{brand.name}</div>
          </div>
        </div>
        <div>
          <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.15, maxWidth: 420 }}>
            Everything in one place.<br/>Fast, simple, visible.
          </div>
          <div style={{ fontSize: 14, marginTop: 16, opacity: 0.75, maxWidth: 380 }}>
            Bookings, schools, invoices, and your content portal — one friendly dashboard built for a busy coach.
          </div>
        </div>
        <div style={{ fontSize: 12, opacity: 0.5 }}>Because every ability matters — and everyone deserves to feel they belong.</div>
      </div>

      <div className="login-panel">
        <div className="login-form">
          <h1 style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", margin: 0 }}>Sign in</h1>
          <p className="muted text-sm" style={{ marginTop: 6 }}>Welcome back — choose how you're signing in.</p>

          <div className="tabs-row" style={{ marginTop: 22, width: "100%" }}>
            <button className={`tab ${role==="admin"?"is-active":""}`} style={{ flex: 1 }} onClick={() => setRole("admin")}>Coach</button>
            <button className={`tab ${role==="super"?"is-active":""}`} style={{ flex: 1 }} onClick={() => setRole("super")}>Super admin</button>
            <button className={`tab ${role==="client"?"is-active":""}`} style={{ flex: 1 }} onClick={() => setRole("client")}>Parent / Teacher</button>
          </div>

          <form onSubmit={handleSubmit} style={{ marginTop: 20 }} className="space-y-3">
            <Field label="Email"><input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} autoComplete="username" /></Field>
            <Field label="Password"><input className="input" type="password" value={pw} onChange={e => setPw(e.target.value)} autoComplete="current-password" /></Field>
            {error && (
              <div style={{ fontSize: 13, color: "oklch(0.55 0.22 25)", background: "oklch(0.96 0.04 25)", border: "1px solid oklch(0.85 0.10 25)", borderRadius: 10, padding: "8px 12px" }}>
                {error}
              </div>
            )}
            <div className="flex items-center justify-between" style={{ fontSize: 12.5 }}>
              <label className="flex items-center gap-2" style={{ cursor: "pointer" }}><span className="cb is-checked"><Icon name="check" size={11} /></span> Remember me</label>
              <a href="#" className="muted">Forgot?</a>
            </div>
            <Button type="submit" variant="primary" size="lg" icon="arrow-right" onClick={handleSubmit} style={{ width: "100%", marginTop: 6 }}>
              Sign in to {role === "client" ? "portal" : "dashboard"}
            </Button>
          </form>

          <div className="muted text-xs" style={{ textAlign: "center", marginTop: 18 }}>
            Don't have an account? <a href="#" style={{ color: "var(--primary)", fontWeight: 600 }}>Request access</a>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- PARENT / TEACHER PORTAL ----------
function ParentPortal({ onExit, onLogout, brand, auth }) {
  const [activeCat, setActiveCat] = React.useState("all");
  const visible = VIDEOS.filter(v => activeCat === "all" || v.cat === activeCat);
  const canSwitchToAdmin = auth && (auth.role === "admin" || auth.role === "super");
  const initials = (auth && auth.avatar) || "SM";

  return (
    <div className="portal-root">
      <header className="portal-header">
        <div className="flex items-center gap-3">
          <BrandMark size={36} />
          <div>
            <div style={{ fontSize: 16, fontWeight: 700 }}>{brand.name}</div>
            <div className="muted text-xs">Content portal — Parent view</div>
          </div>
        </div>
        <div style={{ flex: 1 }}></div>
        <div className="flex items-center gap-3">
          {canSwitchToAdmin && <Button variant="outline" icon="log-in" size="sm" onClick={onExit}>Back to admin</Button>}
          <Button variant="outline" icon="log-out" size="sm" onClick={onLogout}>Log out</Button>
          <div className="avatar">{initials}</div>
        </div>
      </header>

      <main className="portal-content space-y-6">
        <div className="quick-entry-card" style={{ padding: "36px 40px" }}>
          <Chip tone="mint" style={{ marginBottom: 12 }}><Icon name="sparkles" size={12} /> New this week</Chip>
          <div style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-0.02em", maxWidth: 520, marginTop: 10 }}>
            Hello, {(auth && auth.name) ? auth.name.split(" ")[0] : "there"}. Let's move today.
          </div>
          <div className="muted" style={{ marginTop: 8, maxWidth: 520 }}>
            Picked for Charlie — a mix of gentle warm-ups, sensory-friendly games, and the latest "Move Along with Coach Ronan" episode.
          </div>
          <div className="flex gap-2" style={{ marginTop: 18 }}>
            <Button variant="primary" icon="play">Today's session</Button>
            <Button variant="outline" icon="bookmark">My saved videos</Button>
          </div>
        </div>

        <div className="flex items-center justify-between">
          <h2 style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-0.01em", margin: 0 }}>Browse by section</h2>
          <button className="btn btn-ghost btn-sm">All sections <Icon name="arrow-right" size={13} /></button>
        </div>

        <div className="grid-stats" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
          {VIDEO_CATEGORIES.map(c => (
            <div key={c.id} className="card card-lift" style={{ padding: 22, cursor: "pointer" }} onClick={() => setActiveCat(c.id)}>
              <div className={"stat-icon tint-" + c.color} style={{ position: "static", width: 44, height: 44, borderRadius: 13 }}>
                <Icon name={c.icon} size={20} style={{ color: "#fff" }} />
              </div>
              <div style={{ marginTop: 14, fontSize: 16, fontWeight: 700 }}>{c.label}</div>
              <div className="muted text-xs" style={{ marginTop: 3 }}>{c.count} videos · updated weekly</div>
              <div style={{ marginTop: 14, color: "var(--primary)", fontSize: 13, fontWeight: 600, display: "flex", alignItems: "center", gap: 6 }}>
                Browse <Icon name="arrow-right" size={13} />
              </div>
            </div>
          ))}
        </div>

        <div className="flex items-center gap-2 flex-wrap">
          <button className={`filter-pill ${activeCat==="all"?"is-active":""}`} onClick={() => setActiveCat("all")}>All</button>
          {VIDEO_CATEGORIES.map(c => (
            <button key={c.id} className={`filter-pill ${activeCat===c.id?"is-active":""}`} onClick={() => setActiveCat(c.id)}>
              {c.label}
            </button>
          ))}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(230px, 1fr))", gap: 16 }}>
          {visible.map(v => (
            <div key={v.id} className="video-tile">
              <div className="video-thumb" style={{ background: THUMB_ART[v.art - 1] }}>
                <span className="duration">{v.duration}</span>
                <div className="play"><span><Icon name="play" size={20} /></span></div>
              </div>
              <div className="video-body">
                <div className="video-title">{v.title}</div>
                <div className="video-meta">
                  <span>{v.coach}</span>
                  <span>·</span>
                  <span>{v.level}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </main>
    </div>
  );
}

// ---------- TWEAKS PANEL ----------
function TweaksPanel({ brand, setBrand, enabled, onClose, mode, setMode }) {
  if (!enabled) return null;

  const palettes = [
    { name: "FitMinds Coral", primary: "oklch(0.66 0.18 35)" },
    { name: "Indigo Violet",  primary: "oklch(0.50 0.24 264)" },
    { name: "Forest Green",   primary: "oklch(0.55 0.15 160)" },
    { name: "Plum",           primary: "oklch(0.55 0.18 300)" },
    { name: "Ocean Blue",     primary: "oklch(0.55 0.18 230)" },
    { name: "Scarlet",        primary: "oklch(0.60 0.20 25)" },
  ];

  const brands = [
    { name: "FitMindsCoach", tagline: "Inclusive movement coaching" },
    { name: "Northside OT",  tagline: "White-label demo" },
    { name: "Active Kids NI",tagline: "White-label demo" },
  ];

  return (
    <div className="tweaks-panel">
      <div className="tweaks-header">
        <div className="flex items-center gap-2"><Icon name="sliders-horizontal" size={14} /><span style={{ fontWeight: 700 }}>Tweaks</span></div>
        <button className="icon-btn" onClick={onClose} style={{ width: 26, height: 26 }}><Icon name="x" size={13} /></button>
      </div>
      <div className="tweaks-body">
        <div>
          <div className="section-heading" style={{ marginBottom: 8 }}>View</div>
          <div className="tabs-row" style={{ width: "100%" }}>
            <button className={`tab ${mode==="admin"?"is-active":""}`} style={{ flex: 1 }} onClick={() => setMode("admin")}>Admin</button>
            <button className={`tab ${mode==="portal"?"is-active":""}`} style={{ flex: 1 }} onClick={() => setMode("portal")}>Portal</button>
            <button className={`tab ${mode==="login"?"is-active":""}`} style={{ flex: 1 }} onClick={() => setMode("login")}>Login</button>
          </div>
        </div>

        <div>
          <div className="section-heading" style={{ marginBottom: 8 }}>Primary colour</div>
          <div className="swatch-row">
            {palettes.map(p => (
              <div key={p.primary} className={"swatch " + (brand.primary === p.primary ? "is-active" : "")} style={{ background: p.primary }} onClick={() => setBrand({ ...brand, primary: p.primary })} title={p.name}></div>
            ))}
          </div>
        </div>

        <div>
          <div className="section-heading" style={{ marginBottom: 8 }}>White-label preset</div>
          <div className="space-y-3">
            {brands.map(b => (
              <button key={b.name} onClick={() => setBrand({ ...brand, name: b.name, tagline: b.tagline })}
                className={"flex items-center justify-between " + (brand.name === b.name ? "" : "")}
                style={{
                  width: "100%", padding: "10px 12px", borderRadius: 11,
                  border: "1px solid " + (brand.name === b.name ? "var(--primary)" : "var(--border)"),
                  background: brand.name === b.name ? "oklch(.66 .18 35 / .05)" : "var(--card)",
                  cursor: "pointer", fontFamily: "inherit", textAlign: "left",
                }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{b.name}</div>
                  <div className="muted text-xs">{b.tagline}</div>
                </div>
                {brand.name === b.name && <Icon name="check" size={14} style={{ color: "var(--primary)" }} />}
              </button>
            ))}
          </div>
        </div>

        <div>
          <div className="section-heading" style={{ marginBottom: 8 }}>Density</div>
          <div className="tabs-row" style={{ width: "100%" }}>
            <button className={`tab ${brand.density==="cozy"?"is-active":""}`} style={{ flex: 1 }} onClick={() => setBrand({ ...brand, density: "cozy" })}>Cozy</button>
            <button className={`tab ${brand.density==="comfy"?"is-active":""}`} style={{ flex: 1 }} onClick={() => setBrand({ ...brand, density: "comfy" })}>Comfy</button>
            <button className={`tab ${brand.density==="compact"?"is-active":""}`} style={{ flex: 1 }} onClick={() => setBrand({ ...brand, density: "compact" })}>Compact</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function TweaksToggle({ visible, onToggle }) {
  return (
    <button onClick={onToggle} style={{
      position: "fixed", bottom: 20, right: 20, zIndex: 39,
      width: 48, height: 48, borderRadius: 999,
      background: "var(--primary)", color: "#fff", border: "none",
      boxShadow: "var(--shadow-lg)", cursor: "pointer",
      display: visible ? "none" : "inline-flex", alignItems: "center", justifyContent: "center",
    }} title="Open tweaks">
      <Icon name="sliders-horizontal" size={18} />
    </button>
  );
}

Object.assign(window, { LoginPage, ParentPortal, TweaksPanel, TweaksToggle });
