/* Willow Creek Portal — login screen + app shell (role switch, demo store). */
const { PIcon: LIcon, loadStore, saveStore } = window.WCPortal;
const { useState: lUseState, useEffect: lUseEffect } = React;

function LoginScreen({ onLogin }) {
  const { Card, Button, Input, Checkbox, Badge } = window.WillowCreekDesignSystem_90378c;
  const [role, setRole] = lUseState("resident");
  const [email, setEmail] = lUseState("");
  const [pw, setPw] = lUseState("");
  const [busy, setBusy] = lUseState(false);

  const submit = () => {
    setBusy(true);
    setTimeout(() => { setBusy(false); onLogin(role); }, 700);
  };

  return (
    <div style={{ minHeight: "100vh", display: "grid", gridTemplateColumns: "1fr 1.1fr", background: "var(--surface-page)" }} className="wcp-login">
      {/* Brand panel */}
      <div style={{ position: "relative", overflow: "hidden", background: "var(--grad-canopy)", color: "#fffdf8",
        display: "flex", flexDirection: "column", justifyContent: "space-between", padding: "clamp(28px,4vw,56px)" }} className="wcp-login-brand">
        <img src="../assets/logo-wordmark-inverse.svg" alt="Willow Creek Sober Living" style={{ height: 46, alignSelf: "flex-start" }} />
        <div style={{ position: "relative", zIndex: 2 }}>
          <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "var(--text-d2)", letterSpacing: "-0.02em",
            color: "#fffdf8", maxWidth: "14ch", margin: "0 0 14px" }}>One honest day at a time.</h1>
          <p style={{ color: "var(--sage-200)", maxWidth: "40ch", lineHeight: 1.65, margin: 0 }}>
            Pay your program fee, sign house paperwork, and see where you stand — all in one calm place.
          </p>
        </div>
        <div style={{ fontSize: "var(--text-sm)", color: "var(--sage-300)", position: "relative", zIndex: 2, display: "flex", alignItems: "center", gap: 8 }}>
          <LIcon name="lock" size={14} /> Private & confidential
        </div>
        <img src="../assets/logo-mark.svg" alt="" style={{ position: "absolute", right: "-8%", bottom: "-12%", width: 320, opacity: 0.12 }} />
        <div style={{ position: "absolute", top: "-25%", right: "-10%", width: 420, height: 420, borderRadius: "50%",
          background: "radial-gradient(circle, rgba(255,241,214,.25), transparent 65%)" }} />
      </div>

      {/* Form panel */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: "clamp(24px,4vw,56px)" }}>
        <div style={{ width: "100%", maxWidth: 440 }}>
          <h2 style={{ fontSize: "var(--text-d3)", margin: "0 0 6px" }}>Sign in</h2>
          <p style={{ color: "var(--text-muted)", margin: "0 0 22px" }}>Welcome back. We're glad you're here.</p>

          {/* Role toggle */}
          <div role="tablist" style={{ display: "flex", gap: 4, background: "var(--surface-sunken)", padding: 4,
            borderRadius: "var(--radius-md)", marginBottom: 22 }}>
            {[["resident", "user", "Resident"], ["manager", "key-round", "Manager"], ["admin", "shield", "Admin"]].map(([id, icon, label]) => (
              <button key={id} role="tab" aria-selected={role === id} onClick={() => setRole(id)} style={{
                flex: 1, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
                padding: "10px 12px", borderRadius: "var(--radius-sm)", border: "none", cursor: "pointer",
                fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: "var(--text-sm)",
                background: role === id ? "var(--surface-raised)" : "transparent",
                color: role === id ? "var(--brand-primary)" : "var(--text-muted)",
                boxShadow: role === id ? "var(--shadow-sm)" : "none",
                transition: "all var(--dur-fast) var(--ease-out)",
              }}><LIcon name={icon} size={16} /> {label}</button>
            ))}
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Input label="Email" type="email" value={email} onChange={(e) => setEmail(e.target.value)}
              placeholder={role === "resident" ? "marcus@email.com" : role === "manager" ? "james@willowcreeksober.org" : "rebecca@willowcreeksober.org"}
              leftIcon={<LIcon name="mail" size={17} />} />
            <Input label="Password" type="password" value={pw} onChange={(e) => setPw(e.target.value)}
              placeholder="••••••••" leftIcon={<LIcon name="key-round" size={17} />} />
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <Checkbox label="Keep me signed in" defaultChecked />
              <a href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: "var(--text-sm)", fontWeight: 600 }}>Forgot password?</a>
            </div>
            <Button variant="primary" size="lg" fullWidth loading={busy} onClick={submit}
              rightIcon={!busy && <LIcon name="arrow-right" size={18} />}>
              {busy ? "Signing in" : role === "resident" ? "Sign in to my portal" : role === "manager" ? "Sign in as house manager" : "Sign in to admin"}
            </Button>
            {role === "manager" && (
              <p style={{ margin: 0, fontSize: 12, color: "var(--text-muted)", lineHeight: 1.5 }}>
                House managers get minimum admin access: approvals, houses & beds, residents, and payments — no forms builder or rates/site settings.
              </p>
            )}
          </div>

          <div style={{ marginTop: 20, padding: "14px 16px", borderRadius: "var(--radius-md)", background: "var(--surface-water-soft)",
            fontSize: "var(--text-sm)", color: "var(--water-700)", display: "flex", gap: 10, alignItems: "flex-start", lineHeight: 1.55 }}>
            <LIcon name="info" size={16} style={{ marginTop: 2 }} />
            <span>Demo login — any email and password works. Pick a role above and sign in to explore.</span>
          </div>
          <p style={{ textAlign: "center", fontSize: "var(--text-sm)", color: "var(--text-muted)", marginTop: 18 }}>
            New to Willow Creek? <a href="../" style={{ fontWeight: 600 }}>Apply on our website</a>
          </p>
        </div>
      </div>
    </div>
  );
}

/* ---- App shell ---- */
function PortalApp() {
  const [session, setSession] = lUseState(() => {
    try { return localStorage.getItem("wc_portal_session") || null; } catch (e) { return null; }
  });
  const [store, setStoreState] = lUseState(loadStore);
  const setStore = (updater) => {
    setStoreState((prev) => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      saveStore(next);
      return next;
    });
  };
  const login = (role) => {
    setSession(role);
    try { localStorage.setItem("wc_portal_session", role); } catch (e) {}
  };
  const logout = () => {
    setSession(null);
    try { localStorage.removeItem("wc_portal_session"); } catch (e) {}
  };

  if (!session) return <LoginScreen onLogin={login} />;
  if (session === "admin") return <window.WCPortal.AdminPortal role="admin" store={store} setStore={setStore} onLogout={logout} />;
  if (session === "manager") return <window.WCPortal.AdminPortal role="manager" store={store} setStore={setStore} onLogout={logout} />;
  return <window.WCPortal.ResidentPortal store={store} setStore={setStore} user="Marcus Reed" onLogout={logout} />;
}

ReactDOM.createRoot(document.getElementById("app")).render(<PortalApp />);
