// ============================================
// Auth — Splash, Onboarding, Sign Up, Log In, Profile Setup
// ============================================

function SplashScreen({ onDone }) {
  useEffect(() => { const t = setTimeout(onDone, 1800); return () => clearTimeout(t); }, []);
  return (
    <div style={{ position: "fixed", inset: 0, background: "var(--navy-900)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1000 }}>
      <div style={{ position: "relative", width: 200, height: 200 }}>
        {[0, 1, 2].map(i => (
          <div key={i} style={{
            position: "absolute", inset: "50%", width: 0, height: 0,
            border: "2px solid var(--aqua)", borderRadius: "50%",
            animation: `ripple 1.6s ${i * 0.4}s ease-out infinite`,
          }}/>
        ))}
        <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 14 }}>
          <div style={{ width: 76, height: 76, borderRadius: 20, background: "var(--aqua)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 60px rgba(0,153,204,0.5)" }}>
            <Icon name="logo" size={42} color="white"/>
          </div>
          <div style={{ color: "white", fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 26, letterSpacing: -0.5 }}>AquaFlow</div>
          <div style={{ color: "rgba(255,255,255,0.6)", fontSize: 12, letterSpacing: 2, textTransform: "uppercase" }}>Unified Swim Platform</div>
        </div>
      </div>
    </div>
  );
}

const ONB_SLIDES = [
  { headline: "Track every stroke", body: "Lap timers, splits, pace zones — the precision serious swimmers need.", accent: "var(--c-competitive)", icon: "stopwatch", bg: ["#003366", "#0099CC"] },
  { headline: "Train smarter", body: "Guided workouts, GPS routes, brick sessions and weekly goals.", accent: "var(--c-openwater)", icon: "wave", bg: ["#04425b", "#1a7c6e"] },
  { headline: "Manage your school", body: "Class scheduling, attendance, billing and student progress in one place.", accent: "var(--aqua)", icon: "users", bg: ["#04284f", "#06669a"] },
  { headline: "One platform — every swimmer", body: "From a child's first stroke to elite competition. Welcome to AquaFlow.", accent: "var(--mint)", icon: "logo", bg: ["#003366", "#00c9a7"] },
];

function Onboarding({ onDone }) {
  const [i, setI] = useState(0);
  const slide = ONB_SLIDES[i];
  const next = () => i < ONB_SLIDES.length - 1 ? setI(i + 1) : onDone();
  return (
    <div style={{ position: "fixed", inset: 0, background: `linear-gradient(160deg, ${slide.bg[0]}, ${slide.bg[1]})`, zIndex: 900, transition: "background 600ms", display: "flex", flexDirection: "column" }}>
      <div className="between" style={{ padding: 20, color: "white" }}>
        <div className="row">
          <Icon name="logo" size={22} color="white"/>
          <span style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 18 }}>AquaFlow</span>
        </div>
        <button onClick={onDone} style={{ color: "rgba(255,255,255,0.7)", fontSize: 14, fontWeight: 600, padding: 8 }}>Skip</button>
      </div>

      <div style={{ flex: 1, padding: "32px 28px", display: "flex", flexDirection: "column", justifyContent: "flex-end", color: "white", maxWidth: 540, margin: "0 auto", width: "100%" }}>
        <div key={i} className="fade-up" style={{ marginBottom: 32 }}>
          <div style={{ width: 88, height: 88, borderRadius: 24, background: "rgba(255,255,255,0.12)", border: `1.5px solid rgba(255,255,255,0.2)`, display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 28 }}>
            <Icon name={slide.icon} size={44} color="white"/>
          </div>
          <div style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 38, lineHeight: 1.1, letterSpacing: -1, marginBottom: 12 }}>{slide.headline}</div>
          <div style={{ fontSize: 16, lineHeight: 1.5, color: "rgba(255,255,255,0.8)", maxWidth: 420 }}>{slide.body}</div>
        </div>

        <div className="between" style={{ marginTop: 8 }}>
          <div className="row" style={{ gap: 6 }}>
            {ONB_SLIDES.map((_, idx) => (
              <button key={idx} onClick={() => setI(idx)} style={{
                width: idx === i ? 24 : 8, height: 8, borderRadius: 999,
                background: idx === i ? "white" : "rgba(255,255,255,0.4)",
                transition: "all 220ms",
              }}/>
            ))}
          </div>
          <button onClick={next} className="btn btn-mint btn-lg" style={{ paddingInline: 28 }}>
            {i === ONB_SLIDES.length - 1 ? "Get Started" : "Continue"}
            <Icon name="chev-right" size={16}/>
          </button>
        </div>
      </div>
    </div>
  );
}

function LoginScreen({ onLogin, onSignUp, onForgot }) {
  const [email, setEmail] = useState("alex@aquaflow.app");
  const [pw, setPw] = useState("••••••••");
  const [showPw, setShowPw] = useState(false);
  const [busy, setBusy] = useState(false);
  const submit = (e) => {
    e?.preventDefault();
    setBusy(true);
    setTimeout(() => { setBusy(false); onLogin(); }, 600);
  };
  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "stretch" }}>
      <div className="desktop-only" style={{ flex: 1, background: "linear-gradient(160deg, var(--navy-900), var(--teal))", position: "relative", overflow: "hidden", display: "flex", flexDirection: "column", padding: 48 }}>
        <div className="row" style={{ color: "white", gap: 10 }}>
          <Icon name="logo" size={28} color="white"/>
          <span style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 22 }}>AquaFlow</span>
        </div>
        <div style={{ flex: 1, display: "flex", alignItems: "center" }}>
          <div style={{ color: "white", maxWidth: 460 }}>
            <div className="t-display" style={{ marginBottom: 20 }}>Every stroke,<br/>every swimmer,<br/>one platform.</div>
            <div style={{ fontSize: 16, color: "rgba(255,255,255,0.7)", lineHeight: 1.6 }}>From swim school check-ins to elite race splits — AquaFlow brings the entire aquatic world under one roof.</div>
            <div className="row" style={{ marginTop: 32, gap: 24, color: "rgba(255,255,255,0.6)", fontSize: 13 }}>
              <div className="row"><Icon name="check" size={14}/><span>WCAG 2.1 AA</span></div>
              <div className="row"><Icon name="check" size={14}/><span>Offline-first</span></div>
              <div className="row"><Icon name="check" size={14}/><span>API ready</span></div>
            </div>
          </div>
        </div>
        <svg style={{ position: "absolute", bottom: -60, left: -40, opacity: 0.18 }} width="600" height="320" viewBox="0 0 600 320">
          <path d="M0 200 Q150 120 300 200 T 600 200 V320 H0 Z" fill="var(--aqua)"/>
          <path d="M0 240 Q150 160 300 240 T 600 240 V320 H0 Z" fill="var(--mint)"/>
        </svg>
      </div>

      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: 32, background: "white" }}>
        <form onSubmit={submit} style={{ width: "100%", maxWidth: 380 }}>
          <div className="mobile-only" style={{ marginBottom: 32, textAlign: "center" }}>
            <div style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 60, height: 60, borderRadius: 18, background: "var(--navy)", marginBottom: 12 }}>
              <Icon name="logo" size={32} color="white"/>
            </div>
            <div style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 20 }}>AquaFlow</div>
          </div>
          <div className="t-h1" style={{ marginBottom: 6 }}>Welcome back</div>
          <div className="muted" style={{ marginBottom: 24 }}>Log in to continue your training.</div>

          <div className="row" style={{ gap: 8, marginBottom: 18 }}>
            <Button variant="secondary" full icon="google">Google</Button>
            <Button variant="secondary" full icon="apple">Apple</Button>
          </div>
          <div className="row" style={{ gap: 12, marginBottom: 18, color: "var(--gray-500)", fontSize: 12 }}>
            <div style={{ flex: 1, height: 1, background: "var(--gray-200)" }}/>
            <span>or with email</span>
            <div style={{ flex: 1, height: 1, background: "var(--gray-200)" }}/>
          </div>

          <div className="col" style={{ gap: 14, marginBottom: 18 }}>
            <div className="field">
              <label>Email</label>
              <input className="input" value={email} onChange={e => setEmail(e.target.value)} type="email" placeholder="you@example.com"/>
            </div>
            <div className="field">
              <div className="between">
                <label>Password</label>
                <button type="button" onClick={onForgot} style={{ fontSize: 12, color: "var(--aqua)", fontWeight: 600 }}>Forgot?</button>
              </div>
              <div style={{ position: "relative" }}>
                <input className="input" type={showPw ? "text" : "password"} value={pw} onChange={e => setPw(e.target.value)} style={{ width: "100%" }}/>
                <button type="button" onClick={() => setShowPw(!showPw)} style={{ position: "absolute", right: 12, top: 12, color: "var(--gray-500)", fontSize: 12, fontWeight: 600 }}>{showPw ? "Hide" : "Show"}</button>
              </div>
            </div>
          </div>

          <Button type="submit" variant="primary" full size="lg" onClick={submit}>{busy ? "Signing in…" : "Log in"}</Button>

          <div style={{ textAlign: "center", marginTop: 20, fontSize: 13, color: "var(--gray-600)" }}>
            New to AquaFlow? <button type="button" onClick={onSignUp} style={{ color: "var(--aqua)", fontWeight: 600 }}>Create an account</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function SignUpScreen({ onDone, onLogin }) {
  const [role, setRole] = useState("competitive");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [pw, setPw] = useState("");
  const [agree, setAgree] = useState(true);

  const roleOpts = [
    { id: "competitive", label: "Swimmer", icon: "trophy" },
    { id: "recreation", label: "Fitness", icon: "flame" },
    { id: "openwater", label: "Triathlete", icon: "wave" },
    { id: "student", label: "Student", icon: "star" },
    { id: "parent", label: "Parent", icon: "users" },
    { id: "coach", label: "Coach", icon: "swimmer" },
    { id: "admin", label: "Admin", icon: "shield" },
    { id: "developer", label: "Developer", icon: "code" },
  ];

  return (
    <div style={{ minHeight: "100vh", background: "var(--gray-100)", display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
      <div style={{ width: "100%", maxWidth: 500 }}>
        <div style={{ textAlign: "center", marginBottom: 20 }}>
          <div style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 60, height: 60, borderRadius: 18, background: "var(--navy)", marginBottom: 12 }}>
            <Icon name="logo" size={32} color="white"/>
          </div>
          <div className="t-h1">Create your AquaFlow account</div>
          <div className="muted">Free to start — premium features unlock per role.</div>
        </div>

        <div className="card" style={{ padding: 24 }}>
          <div className="row" style={{ gap: 8, marginBottom: 18 }}>
            <Button variant="secondary" full icon="google">Google</Button>
            <Button variant="secondary" full icon="apple">Apple</Button>
          </div>
          <div className="row" style={{ gap: 12, marginBottom: 18, color: "var(--gray-500)", fontSize: 12 }}>
            <div style={{ flex: 1, height: 1, background: "var(--gray-200)" }}/>
            <span>or with email</span>
            <div style={{ flex: 1, height: 1, background: "var(--gray-200)" }}/>
          </div>

          <div className="col" style={{ gap: 12, marginBottom: 18 }}>
            <div className="field">
              <label>I'm a…</label>
              <div style={{ display: "flex", gap: 6, overflowX: "auto", paddingBottom: 4, marginInline: -4, paddingInline: 4 }}>
                {roleOpts.map(r => {
                  const active = role === r.id;
                  return (
                    <button key={r.id} type="button" onClick={() => setRole(r.id)} style={{
                      flexShrink: 0, padding: "8px 14px", borderRadius: 999,
                      background: active ? "var(--navy)" : "var(--gray-100)",
                      color: active ? "white" : "var(--gray-700)",
                      fontSize: 13, fontWeight: 600, display: "flex", alignItems: "center", gap: 6,
                    }}>
                      <Icon name={r.icon} size={14}/>
                      {r.label}
                    </button>
                  );
                })}
              </div>
            </div>
            <div className="field">
              <label>Full name</label>
              <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Alex Rivera"/>
            </div>
            <div className="field">
              <label>Email</label>
              <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com"/>
            </div>
            <div className="field">
              <label>Password</label>
              <input className="input" type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="At least 8 characters"/>
            </div>
          </div>

          <label className="row" style={{ marginBottom: 18, fontSize: 13, color: "var(--gray-700)", alignItems: "flex-start", gap: 10 }}>
            <input type="checkbox" checked={agree} onChange={e => setAgree(e.target.checked)} style={{ marginTop: 2 }}/>
            <span>I agree to the <a>Terms of Service</a> and <a>Privacy Policy</a>. Parents creating accounts for minors confirm their consent.</span>
          </label>

          <Button variant="primary" full size="lg" onClick={onDone}>Create Account</Button>

          <div style={{ textAlign: "center", marginTop: 16, fontSize: 13, color: "var(--gray-600)" }}>
            Already have an account? <button onClick={onLogin} style={{ color: "var(--aqua)", fontWeight: 600 }}>Log in</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function ProfileSetupWizard({ onDone, role }) {
  const [step, setStep] = useState(0);
  const [units, setUnits] = useState("metric");
  const [pool, setPool] = useState("25m");

  return (
    <div style={{ minHeight: "100vh", background: "var(--gray-100)", display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
      <div className="card" style={{ width: "100%", maxWidth: 500, padding: 28 }}>
        <div className="row" style={{ gap: 6, marginBottom: 24, justifyContent: "center" }}>
          {[0, 1, 2].map(i => (
            <div key={i} style={{ width: i === step ? 32 : 10, height: 10, borderRadius: 999, background: i <= step ? "var(--aqua)" : "var(--gray-200)", transition: "all 220ms" }}/>
          ))}
        </div>

        {step === 0 && (
          <div>
            <div className="t-h1" style={{ marginBottom: 6 }}>Tell us about you</div>
            <div className="muted" style={{ marginBottom: 24 }}>This helps us personalize your dashboard.</div>

            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, marginBottom: 24 }}>
              <Avatar name="Alex Rivera" size="lg"/>
              <button className="btn btn-secondary btn-sm" type="button"><Icon name="upload" size={14}/>Upload photo</button>
            </div>
            <div className="col" style={{ gap: 12 }}>
              <div className="field"><label>Display name</label><input className="input" defaultValue="Alex Rivera"/></div>
              <div className="row" style={{ gap: 12 }}>
                <div className="field" style={{ flex: 1 }}><label>Date of birth</label><input className="input" type="date" defaultValue="1995-04-12"/></div>
                <div className="field" style={{ flex: 1 }}><label>Country</label><select className="select"><option>Singapore</option><option>Australia</option><option>USA</option><option>UK</option></select></div>
              </div>
            </div>
          </div>
        )}

        {step === 1 && (
          <div>
            <div className="t-h1" style={{ marginBottom: 6 }}>Your swim profile</div>
            <div className="muted" style={{ marginBottom: 24 }}>We'll fine-tune your modules around this.</div>
            <div className="col" style={{ gap: 16 }}>
              <div className="field">
                <label>Primary stroke</label>
                <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
                  {["Freestyle", "Backstroke", "Breaststroke", "Butterfly", "IM"].map(s => (
                    <Pill key={s} tone="aqua">{s}</Pill>
                  ))}
                </div>
              </div>
              <div className="field">
                <label>Current level</label>
                <select className="select"><option>Level 7 — Stroke Refinement</option><option>Level 5</option><option>Masters</option><option>Open</option></select>
              </div>
              <div className="field">
                <label>Home pool / location</label>
                <input className="input" defaultValue="Aqua Center Pool — Lane 4"/>
              </div>
              <div className="field">
                <label>Weekly volume goal</label>
                <input className="input" type="number" defaultValue="12000"/>
                <div className="t-caption">Total meters per week. You can change this later.</div>
              </div>
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <div className="t-h1" style={{ marginBottom: 6 }}>Preferences</div>
            <div className="muted" style={{ marginBottom: 24 }}>Final touches.</div>

            <div className="col" style={{ gap: 14 }}>
              <div className="field">
                <label>Units</label>
                <div className="row" style={{ gap: 8 }}>
                  {["metric", "imperial"].map(u => (
                    <button key={u} onClick={() => setUnits(u)} className="btn" style={{ flex: 1, background: units === u ? "var(--navy)" : "white", color: units === u ? "white" : "var(--gray-700)", border: `1px solid ${units === u ? "var(--navy)" : "var(--gray-300)"}` }}>{u === "metric" ? "Metric (m, kg)" : "Imperial (yd, lb)"}</button>
                  ))}
                </div>
              </div>
              <div className="field">
                <label>Default pool length</label>
                <div className="row" style={{ gap: 8 }}>
                  {["25m", "50m", "25y"].map(p => (
                    <button key={p} onClick={() => setPool(p)} className="btn" style={{ flex: 1, background: pool === p ? "var(--navy)" : "white", color: pool === p ? "white" : "var(--gray-700)", border: `1px solid ${pool === p ? "var(--navy)" : "var(--gray-300)"}` }}>{p}</button>
                  ))}
                </div>
              </div>
              <div className="between" style={{ padding: "10px 0", borderTop: "1px solid var(--gray-200)" }}>
                <div><div style={{ fontWeight: 600, fontSize: 14 }}>Push notifications</div><div className="t-caption">Class reminders, achievements, messages</div></div>
                <Toggle on={true} onChange={() => {}}/>
              </div>
              <div className="between" style={{ padding: "10px 0", borderTop: "1px solid var(--gray-200)" }}>
                <div><div style={{ fontWeight: 600, fontSize: 14 }}>Haptic feedback</div><div className="t-caption">Vibrate on lap taps & milestones</div></div>
                <Toggle on={true} onChange={() => {}}/>
              </div>
              <div className="between" style={{ padding: "10px 0", borderTop: "1px solid var(--gray-200)" }}>
                <div><div style={{ fontWeight: 600, fontSize: 14 }}>Health app sync</div><div className="t-caption">Apple Health / Google Fit</div></div>
                <Toggle on={false} onChange={() => {}}/>
              </div>
            </div>
          </div>
        )}

        <div className="row" style={{ marginTop: 24, gap: 10 }}>
          {step > 0 && <Button variant="ghost" onClick={() => setStep(step - 1)}>Back</Button>}
          <div style={{ flex: 1 }}/>
          <Button variant="primary" size="lg" onClick={() => step < 2 ? setStep(step + 1) : onDone()}>
            {step < 2 ? "Continue" : "Finish setup"}
            <Icon name="chev-right" size={14}/>
          </Button>
        </div>
      </div>
    </div>
  );
}

function ForgotPasswordScreen({ onBack }) {
  const [sent, setSent] = useState(false);
  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", padding: 24, background: "var(--gray-100)" }}>
      <div className="card" style={{ maxWidth: 420, width: "100%", padding: 28 }}>
        {!sent ? (
          <>
            <div className="t-h1" style={{ marginBottom: 6 }}>Reset password</div>
            <div className="muted" style={{ marginBottom: 20 }}>Enter your email and we'll send a reset link.</div>
            <div className="field" style={{ marginBottom: 16 }}>
              <label>Email</label>
              <input className="input" type="email" defaultValue="alex@aquaflow.app"/>
            </div>
            <Button variant="primary" full size="lg" onClick={() => setSent(true)}>Send Reset Link</Button>
            <button onClick={onBack} className="btn btn-ghost btn-full" style={{ marginTop: 10 }}><Icon name="chev-left" size={14}/>Back to log in</button>
          </>
        ) : (
          <div style={{ textAlign: "center", padding: "12px 0" }}>
            <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--mint-50)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
              <Icon name="mail" size={28} color="var(--mint)"/>
            </div>
            <div className="t-h1" style={{ marginBottom: 6 }}>Check your inbox</div>
            <div className="muted" style={{ marginBottom: 18 }}>We've sent a reset link to your email. It will expire in 30 minutes.</div>
            <Button variant="primary" full onClick={onBack}>Back to log in</Button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SplashScreen, Onboarding, LoginScreen, SignUpScreen, ProfileSetupWizard, ForgotPasswordScreen });
