// Login + Onboarding
const Link = ReactRouterDOM.Link;

function LoginPage() {
  const [email, setEmail] = useState("");
  const [pwd, setPwd] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    const res = await signInWithPassword(email.trim(), pwd);
    setLoading(false);
    if (res.error) {
      setError(res.error.message || "Sign in failed");
      return;
    }
    // AuthProvider's onAuthStateChange picks up the new session and reroutes.
  };

  return (
    <div className="min-h-screen flex grain bg-paper">
      {/* Left — form */}
      <div className="flex-1 flex flex-col px-8 lg:px-16 py-8">
        <div className="flex items-center gap-2.5">
          <div className="h-8 w-8 grid place-items-center rounded-xl bg-ink"><VMark size={15} color="#FFFFFF" /></div>
          <span className="font-display text-[20px]">Vale</span>
          <span className="text-[10px] uppercase tracking-[0.14em] text-ink/45 ml-1">Booking</span>
        </div>

        <div className="flex-1 flex items-center">
          <div className="w-full max-w-[380px]">
            <h1 className="font-display text-[44px] leading-[1.05]">Welcome back</h1>
            <p className="mt-2 text-[14px] text-ink/55">Sign in to manage bookings, events, and customers for your business.</p>

            <button type="button" className="mt-7 w-full h-11 rounded-full bg-white border border-ink/[0.15] hover:bg-ink/[0.02] text-ink inline-flex items-center justify-center gap-2.5 font-medium text-[13.5px] shadow-card">
              <svg width="15" height="15" viewBox="0 0 48 48" aria-hidden="true">
                <path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.4 29.3 35.5 24 35.5c-6.4 0-11.5-5.1-11.5-11.5S17.6 12.5 24 12.5c2.9 0 5.6 1.1 7.7 2.9l5.7-5.7C33.6 6.5 29 4.5 24 4.5 13.2 4.5 4.5 13.2 4.5 24S13.2 43.5 24 43.5 43.5 34.8 43.5 24c0-1.2-.1-2.4-.4-3.5z"/>
                <path fill="#FF3D00" d="m6.3 14.7 6.6 4.8C14.6 16.2 19 12.5 24 12.5c2.9 0 5.6 1.1 7.7 2.9l5.7-5.7C33.6 6.5 29 4.5 24 4.5 16.1 4.5 9.3 8.7 6.3 14.7z"/>
                <path fill="#4CAF50" d="M24 43.5c5 0 9.6-1.9 13-5l-6-5.1C29.2 34.7 26.7 35.5 24 35.5c-5.3 0-9.7-3.1-11.3-7.5l-6.5 5C9.3 39.3 16.1 43.5 24 43.5z"/>
                <path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.1-4 5.5l6 5.1c-.4.4 6.4-4.7 6.4-14.1 0-1.2-.1-2.4-.4-3.5z"/>
              </svg>
              Continue with Google
            </button>

            <div className="my-5 flex items-center gap-3 text-[11px] text-ink/40 uppercase tracking-[0.12em]">
              <div className="flex-1 h-px bg-ink/10" />
              or
              <div className="flex-1 h-px bg-ink/10" />
            </div>

            <form onSubmit={submit} className="flex flex-col gap-3.5">
              <Field label="Email">
                <Input type="email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
              </Field>
              <Field label="Password" action={<a href="#" className="text-[11px] text-ink/55 hover:text-ink">Forgot password?</a>}>
                <Input type="password" autoComplete="current-password" value={pwd} onChange={(e) => setPwd(e.target.value)} required />
              </Field>
              {error && (
                <div className="text-[12px] text-danger bg-danger/[0.06] border border-danger/15 rounded-md px-3 py-2">{error}</div>
              )}
              <Button type="submit" size="lg" disabled={loading || !email || !pwd}>
                {loading ? <><span className="h-2 w-2 rounded-full bg-white pulse-dot" />Signing in…</> : "Sign in"}
              </Button>
            </form>

            <div className="mt-6 text-[12.5px] text-ink/55">
              Owner invited by Vale? Sign in with the email and password we sent you.
            </div>
          </div>
        </div>

        <div className="text-[11px] text-ink/40 flex items-center gap-4">
          <span>© Vale Studio</span>
          <a href="#" className="hover:text-ink/70">Privacy</a>
          <a href="#" className="hover:text-ink/70">Terms</a>
          <a href="#" className="hover:text-ink/70">Status</a>
        </div>
      </div>

      {/* Right — quote panel */}
      <div className="hidden lg:flex flex-1 relative border-l border-ink/[0.06] grain">
        <div className="absolute inset-0 dotgrid opacity-50" />
        <div className="relative m-auto max-w-md p-10">
          <div className="text-[11px] uppercase tracking-[0.14em] text-ink/40">A note from Vale</div>
          <p className="mt-5 font-display text-[34px] leading-[1.15] text-ink">
            <span className="italic">“We design the website.</span> Vale Booking handles the rest — so the front of house feels as considered as the front page.”
          </p>
          <div className="mt-6 flex items-center gap-3">
            <div className="h-10 w-10 rounded-full bg-ink/[0.06] border border-ink/[0.08]" />
            <div>
              <div className="text-[13px]">Vale Studio</div>
              <div className="text-[12px] text-ink/45">Brooklyn · Lisbon · Tokyo</div>
            </div>
          </div>
          <div className="mt-10 grid grid-cols-3 gap-3">
            {["Granite","Linen","Pearl"].map((t) => (
              <div key={t} className="aspect-[3/4] rounded-md border border-ink/[0.06] placeholder-stripes flex items-end p-2">
                <span className="text-[10px] uppercase tracking-[0.1em] text-ink/55">{t}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Onboarding ────────────────────────────────────────────────────────────
const ONBOARD_STEPS = [
  { id: 1, label: "Business profile" },
  { id: 2, label: "Modules" },
  { id: 3, label: "Hours" },
  { id: 4, label: "First booking form" }
];

function OnboardingPage() {
  const navigate = ReactRouterDOM.useNavigate();
  const [step, setStep] = useState(1);
  const [data, setData] = useState({
    name: "", industry: "Powersports", url: "", timezone: "America/Denver",
    modules: { bookings: true, events: true, customers: true, automations: true },
    hours: { mon: "9–17", tue: "9–17", wed: "9–17", thu: "9–17", fri: "9–17", sat: "10–14", sun: "Closed" },
    formName: "Schedule Service"
  });

  const next = () => step < 4 ? setStep(step + 1) : navigate("/app/dashboard");
  const back = () => step > 1 ? setStep(step - 1) : navigate("/login");

  return (
    <div className="min-h-screen flex flex-col bg-paper">
      {/* Header */}
      <header className="border-b border-ink/[0.06]">
        <div className="max-w-6xl mx-auto px-6 lg:px-10 h-14 flex items-center gap-3">
          <div className="flex items-center gap-2.5">
            <div className="h-7 w-7 grid place-items-center rounded-lg bg-ink"><VMark size={13} color="#FFFFFF" /></div>
            <span className="font-display text-[18px]">Vale</span>
          </div>
          <div className="text-[11px] uppercase tracking-[0.12em] text-ink/40 ml-3">Workspace setup</div>
          <div className="ml-auto text-[12px] text-ink/55">Step {step} of 4</div>
        </div>
      </header>

      <div className="flex-1 max-w-6xl w-full mx-auto px-6 lg:px-10 py-10 grid lg:grid-cols-[260px_1fr] gap-10">
        {/* Stepper */}
        <aside className="hidden lg:block">
          <ol className="flex flex-col gap-1">
            {ONBOARD_STEPS.map((s) => {
              const done = step > s.id, active = step === s.id;
              return (
                <li key={s.id} className={`flex items-center gap-3 px-3 py-2.5 rounded-md ${active ? "bg-ink/[0.04]" : ""}`}>
                  <span className={`h-6 w-6 grid place-items-center rounded-full text-[11px] ${done ? "bg-ok/30 text-[#86C9A6]" : active ? "bg-accent text-white" : "bg-ink/[0.04] text-ink/50"}`}>
                    {done ? <Icon name="check" size={11} /> : s.id}
                  </span>
                  <span className={`text-[13px] ${active ? "text-ink" : "text-ink/55"}`}>{s.label}</span>
                </li>
              );
            })}
          </ol>
          <div className="mt-8 p-4 rounded-lg border border-ink/[0.06] bg-white">
            <div className="text-[11px] uppercase tracking-[0.1em] text-ink/45 mb-2">Need help?</div>
            <p className="text-[12.5px] text-ink/70">Your Vale account manager is on standby. Most workspaces are configured in under five minutes.</p>
          </div>
        </aside>

        {/* Body */}
        <div className="max-w-2xl">
          {step === 1 && (
            <div>
              <h2 className="font-display text-[34px] leading-tight">Tell us about your business</h2>
              <p className="mt-2 text-[13.5px] text-ink/55">We'll use these details to set up your workspace and align with the website Vale has designed for you.</p>
              <div className="mt-7 grid sm:grid-cols-2 gap-4">
                <Field label="Business name" required><Input placeholder="Northstone Powersports" value={data.name} onChange={(e)=>setData({...data,name:e.target.value})} /></Field>
                <Field label="Industry" required>
                  <Select value={data.industry} onChange={(e)=>setData({...data,industry:e.target.value})}>
                    {["Powersports","Restaurant","Dentist","Doctor","Rental","Wellness","Other"].map(o => <option key={o}>{o}</option>)}
                  </Select>
                </Field>
                <Field label="Website URL" required hint="The site Vale built for you">
                  <Input placeholder="northstone-powersports.com" value={data.url} onChange={(e)=>setData({...data,url:e.target.value})} />
                </Field>
                <Field label="Timezone" required>
                  <Select value={data.timezone} onChange={(e)=>setData({...data,timezone:e.target.value})}>
                    {["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Paris","Asia/Tokyo"].map(o => <option key={o}>{o}</option>)}
                  </Select>
                </Field>
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <h2 className="font-display text-[34px] leading-tight">Choose your modules</h2>
              <p className="mt-2 text-[13.5px] text-ink/55">Enable the parts of Vale Booking you'll use. You can change this later.</p>
              <div className="mt-7 grid sm:grid-cols-2 gap-3">
                {[
                  { id: "bookings", title: "Bookings & Calendar", desc: "Service appointments, availability, calendar sync.", icon: "calendar" },
                  { id: "events", title: "Events", desc: "Workshops, classes, and one-off signups.", icon: "ticket" },
                  { id: "customers", title: "Customer profiles", desc: "Contact history, tags, internal notes.", icon: "users" },
                  { id: "automations", title: "Automations", desc: "Confirmations, reminders, and owner alerts.", icon: "send" }
                ].map((m) => {
                  const on = data.modules[m.id];
                  return (
                    <button
                      key={m.id}
                      onClick={() => setData({...data, modules: { ...data.modules, [m.id]: !on }})}
                      className={`text-left rounded-lg border p-4 transition ${on ? "border-accent/50 bg-accent/[0.06]" : "border-ink/[0.08] bg-white hover:bg-white"}`}
                    >
                      <div className="flex items-start justify-between">
                        <Icon name={m.icon} size={18} className={on ? "text-accent" : "text-ink/55"} />
                        <LocalToggle defaultChecked={on} size="sm" />
                      </div>
                      <div className="mt-3 font-medium text-[14px]">{m.title}</div>
                      <div className="text-[12.5px] text-ink/55 mt-1">{m.desc}</div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {step === 3 && (
            <div>
              <h2 className="font-display text-[34px] leading-tight">When are you open?</h2>
              <p className="mt-2 text-[13.5px] text-ink/55">Default business hours. You can override specific dates from your calendar later.</p>
              <div className="mt-7 rounded-lg border border-ink/[0.06] divide-y divide-ink/[0.06] overflow-hidden">
                {[
                  ["mon","Monday"],["tue","Tuesday"],["wed","Wednesday"],["thu","Thursday"],
                  ["fri","Friday"],["sat","Saturday"],["sun","Sunday"]
                ].map(([k,label]) => (
                  <div key={k} className="flex items-center gap-3 px-4 py-3">
                    <span className="text-[13px] w-24">{label}</span>
                    <Toggle checked={data.hours[k] !== "Closed"} onChange={(v) => setData({...data, hours:{...data.hours, [k]: v ? "9–17" : "Closed"}})} size="sm" />
                    {data.hours[k] !== "Closed" ? (
                      <div className="flex items-center gap-2 ml-2">
                        <Input className="!h-7 !text-[12px] w-20" defaultValue="09:00" />
                        <span className="text-ink/40 text-[12px]">–</span>
                        <Input className="!h-7 !text-[12px] w-20" defaultValue="17:00" />
                      </div>
                    ) : (
                      <span className="text-[12px] text-ink/40 ml-2">Closed</span>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {step === 4 && (
            <div>
              <h2 className="font-display text-[34px] leading-tight">Set up your first booking form</h2>
              <p className="mt-2 text-[13.5px] text-ink/55">You can use a template tuned to your industry, or start from scratch.</p>
              <Field label="Form name" required className="mt-7">
                <Input value={data.formName} onChange={(e)=>setData({...data,formName:e.target.value})} placeholder="Schedule Service" />
              </Field>
              <div className="mt-5 text-[12px] uppercase tracking-[0.1em] text-ink/45">Start from a template</div>
              <div className="mt-3 grid sm:grid-cols-2 gap-3">
                {window.VB.industryTemplates.slice(0,4).map((t) => (
                  <button key={t.id} className="text-left rounded-lg border border-ink/[0.08] bg-white p-4 hover:bg-white">
                    <div className="flex items-center justify-between">
                      <span className="font-medium text-[13.5px]">{t.name}</span>
                      <Badge tone="neutral">{t.fields} fields</Badge>
                    </div>
                    <div className="text-[12px] text-ink/55 mt-1.5">{t.desc}</div>
                  </button>
                ))}
              </div>
              <LockedNotice className="mt-6" text="Visual styling for your booking card is controlled by your Vale website template. You'll be editing content and questions only." />
            </div>
          )}

          {/* Nav */}
          <div className="mt-9 flex items-center justify-between">
            <Button variant="ghost" icon="arrow-left" onClick={back}>Back</Button>
            <div className="flex items-center gap-3">
              <div className="hidden sm:flex items-center gap-1.5">
                {ONBOARD_STEPS.map((s) => (
                  <span key={s.id} className={`h-1 w-8 rounded-full ${step >= s.id ? "bg-accent" : "bg-ink/[0.08]"}`} />
                ))}
              </div>
              <Button iconRight={step === 4 ? "check" : "arrow-right"} onClick={next}>
                {step === 4 ? "Enter dashboard" : "Continue"}
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginPage, OnboardingPage });
