// Website Install, Automations, Settings — all backed by Supabase, scoped to
// the current workspace.

// ── Website Install ──────────────────────────────────────────────────────
function WebsiteInstallPage() {
  const auth = useAuth();
  const toast = useToast();
  const ws = auth.currentWorkspace;

  const [forms, setForms] = useState([]);
  const [loading, setLoading] = useState(true);
  const [embedHost, setEmbedHost] = useState(window.location.origin);

  useEffect(() => {
    if (!ws?.id) { setLoading(false); return; }
    let cancelled = false;
    (async () => {
      const res = await SB.from('forms')
        .select('id, name, public_title, published')
        .eq('workspace_id', ws.id)
        .is('archived_at', null)
        .order('created_at');
      if (cancelled) return;
      setLoading(false);
      setForms(res.data || []);
    })();
    return () => { cancelled = true; };
  }, [ws?.id]);

  if (!ws) return null;

  const publicUrl = `${embedHost}/#/public/${ws.slug}`;
  const publishedForms = forms.filter(f => f.published);
  const iframeSnippet =
`<iframe
  src="${publicUrl}"
  width="100%"
  height="900"
  frameborder="0"
  style="border:0;max-width:100%;display:block"
  title="${ws.name} — Book an appointment"
></iframe>`;
  const buttonSnippet =
`<a href="${publicUrl}" target="_blank" rel="noopener" style="display:inline-block;padding:14px 24px;background:#1D1D1F;color:#fff;text-decoration:none;border-radius:999px;font-family:-apple-system,system-ui,sans-serif;font-size:14px;font-weight:500">Book an appointment</a>`;

  const copy = async (text, label) => {
    try { await navigator.clipboard.writeText(text); toast.push(`${label} copied`); }
    catch { toast.push("Couldn't copy — please select manually"); }
  };

  const isLocal = /^http:\/\/(localhost|127\.|0\.0\.0\.0)/.test(embedHost);

  return (
    <div className="px-5 lg:px-7 py-7 max-w-[1400px] mx-auto">
      <PageHeader
        eyebrow="Connection"
        title="Website"
        subtitle="Public booking URL + the embed snippet to paste onto the customer's site."
        actions={<Button variant="secondary" icon="external-link" onClick={() => window.open(`#/public/${ws.slug}`, "_blank")}>Open public page</Button>}
      />

      {loading ? (
        <div className="py-16 text-center text-[12.5px] text-ink/50">Loading…</div>
      ) : (
        <div className="grid lg:grid-cols-[1fr_360px] gap-6">
          <div className="flex flex-col gap-5">
            <div className="rounded-lg border border-ink/[0.06] bg-white p-5">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3 min-w-0">
                  <div className="h-10 w-10 rounded-md bg-ink/[0.04] grid place-items-center flex-shrink-0">
                    <Icon name="globe" size={16} />
                  </div>
                  <div className="min-w-0">
                    <div className="text-[13.5px] font-medium truncate">{ws.name}</div>
                    <div className="text-[12px] text-ink/55">
                      {publishedForms.length === 0
                        ? "No published forms — publish at least one to take bookings."
                        : `${publishedForms.length} published form${publishedForms.length === 1 ? "" : "s"}`}
                    </div>
                  </div>
                </div>
                {publishedForms.length > 0
                  ? <Badge tone="ok" dot>Live</Badge>
                  : <Badge tone="warn" dot>No forms published</Badge>}
              </div>

              <div className="mt-5 grid sm:grid-cols-2 gap-4">
                <KV label="Public URL">
                  <div className="flex items-center gap-2 font-mono text-[12px] truncate">
                    <span className="truncate">{publicUrl}</span>
                    <button onClick={() => copy(publicUrl, "Public URL")} className="text-ink/55 hover:text-ink flex-shrink-0"><Icon name="copy" size={11} /></button>
                  </div>
                </KV>
                <KV label="Workspace slug">
                  <span className="font-mono text-[12.5px]">{ws.slug}</span>
                </KV>
                <KV label="Timezone">{ws.timezone || "—"}</KV>
                <KV label="Industry"><span className="capitalize">{ws.industry || "other"}</span></KV>
              </div>
            </div>

            <div className="rounded-lg border border-ink/[0.06] bg-white p-5">
              <div className="text-[11px] uppercase tracking-[0.1em] text-ink/50 mb-2">Embed host</div>
              <p className="text-[12.5px] text-ink/55 mb-3">
                The URL the snippets below point at. Defaults to your current host. After deploying to your own domain (e.g. <span className="font-mono">app.vale.codes</span>), update this so the snippets use the production URL.
              </p>
              <div className="flex items-center gap-2">
                <Input value={embedHost} onChange={(e) => setEmbedHost(e.target.value.replace(/\/+$/, ""))} placeholder="https://app.vale.codes" />
                <Button size="sm" variant="ghost" onClick={() => setEmbedHost(window.location.origin)}>Reset</Button>
              </div>
              {isLocal && (
                <div className="mt-3 text-[11.5px] text-warn flex items-start gap-1.5">
                  <Icon name="alert-triangle" size={12} className="mt-0.5" />
                  <span>This is a localhost URL — fine for testing, but external websites can't reach it. Update before pasting into a live site.</span>
                </div>
              )}
            </div>

            <div className="rounded-lg border border-ink/[0.06] bg-white p-5">
              <div className="flex items-center justify-between mb-2">
                <div>
                  <div className="text-[13.5px] font-medium">Iframe embed</div>
                  <div className="text-[12px] text-ink/55">Paste anywhere on the client's site where the booking card should appear.</div>
                </div>
                <Button size="sm" variant="secondary" icon="copy" onClick={() => copy(iframeSnippet, "Iframe snippet")}>Copy</Button>
              </div>
              <pre className="mt-3 rounded-md border border-ink/[0.06] bg-ink p-3 font-mono text-[11.5px] text-white/85 overflow-x-auto whitespace-pre">{iframeSnippet}</pre>
            </div>

            <div className="rounded-lg border border-ink/[0.06] bg-white p-5">
              <div className="flex items-center justify-between mb-2">
                <div>
                  <div className="text-[13.5px] font-medium">Button link</div>
                  <div className="text-[12px] text-ink/55">A simpler "Book now" button that opens the booking page in a new tab.</div>
                </div>
                <Button size="sm" variant="secondary" icon="copy" onClick={() => copy(buttonSnippet, "Button snippet")}>Copy</Button>
              </div>
              <pre className="mt-3 rounded-md border border-ink/[0.06] bg-ink p-3 font-mono text-[11.5px] text-white/85 overflow-x-auto whitespace-pre">{buttonSnippet}</pre>
            </div>

            <div className="rounded-lg border border-ink/[0.06] bg-white p-5">
              <div className="text-[11px] uppercase tracking-[0.1em] text-ink/50 mb-3">Forms visible on the public page</div>
              {forms.length === 0 ? (
                <div className="text-[12.5px] text-ink/45">No forms yet. Create one under <a href="#/app/forms" className="text-ink underline">Booking Forms</a>.</div>
              ) : (
                <div className="flex flex-col divide-y divide-ink/[0.06]">
                  {forms.map(f => (
                    <div key={f.id} className="flex items-center justify-between py-2.5">
                      <div className="min-w-0">
                        <div className="text-[13px] truncate">{f.public_title || f.name}</div>
                        <div className="text-[11.5px] text-ink/50 truncate">{f.name}</div>
                      </div>
                      {f.published ? <Badge tone="ok" dot>Published</Badge> : <Badge tone="neutral">Draft</Badge>}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          <aside>
            <div className="text-[11px] uppercase tracking-[0.1em] text-ink/45 mb-3 flex items-center gap-2">
              <Icon name="eye" size={12} /> Live preview
            </div>
            <div className="rounded-lg border border-ink/[0.08] bg-white overflow-hidden shadow-card">
              <div className="bg-ink/[0.04] border-b border-ink/[0.06] px-3 py-2 flex items-center gap-2">
                <div className="flex items-center gap-1">
                  <span className="h-2 w-2 rounded-full bg-ink/15" />
                  <span className="h-2 w-2 rounded-full bg-ink/15" />
                  <span className="h-2 w-2 rounded-full bg-ink/15" />
                </div>
                <div className="ml-1 text-[10.5px] text-ink/45 font-mono truncate">{publicUrl.replace(/^https?:\/\//, "")}</div>
              </div>
              {publishedForms.length === 0 ? (
                <div className="p-6 text-center text-[12.5px] text-ink/55">
                  Publish a form to see the live preview.
                </div>
              ) : (
                <iframe
                  src={`#/public/${ws.slug}`}
                  className="w-full h-[560px] block"
                  title={`${ws.name} preview`}
                />
              )}
            </div>
            <p className="mt-3 text-[11.5px] text-ink/45">
              This is the exact same page customers see at the public URL.
            </p>
          </aside>
        </div>
      )}
    </div>
  );
}

function KV({ label, children }) {
  return (
    <div>
      <div className="text-[10.5px] uppercase tracking-[0.1em] text-ink/45 mb-1">{label}</div>
      <div className="text-[13px]">{children}</div>
    </div>
  );
}

// ── Automations ──────────────────────────────────────────────────────────
// User-facing labels for each automation kind. Order here also drives display.
const AUTOMATION_DEFS = [
  { kind: "booking_confirmed",   name: "Booking confirmed",       to: "customer", desc: "Sent when you accept a booking request." },
  { kind: "booking_declined",    name: "Booking declined",        to: "customer", desc: "Sent when you decline a request." },
  { kind: "reschedule_proposed", name: "Reschedule proposed",     to: "customer", desc: "Sent when you propose a new time." },
  { kind: "cancellation",        name: "Cancellation",            to: "customer", desc: "Sent when a confirmed booking is cancelled." },
  { kind: "reminder_24h",        name: "Reminder · 24h before",   to: "customer", desc: "Auto-sent the day before the appointment." },
  { kind: "reminder_2h",         name: "Reminder · 2h before",    to: "customer", desc: "Auto-sent two hours before the appointment." },
  { kind: "event_signup",        name: "Event signup",            to: "customer", desc: "Sent when someone signs up for an event." },
  { kind: "owner_new_booking",   name: "New booking · to you",    to: "owner",    desc: "Notification when a new request comes in." }
];

const TEMPLATE_VARS = [
  "{{first_name}}", "{{customer}}", "{{date}}", "{{time}}",
  "{{service}}", "{{business}}", "{{proposed_date}}", "{{proposed_time}}", "{{event}}"
];

function AutomationsPage() {
  const auth = useAuth();
  const ws = auth.currentWorkspace;
  const toast = useToast();

  const [byKind, setByKind] = useState({});
  const [loading, setLoading] = useState(true);
  const [editKind, setEditKind] = useState(null);

  useEffect(() => {
    if (!ws?.id) { setLoading(false); return; }
    let cancelled = false;
    (async () => {
      const res = await SB.from('automations').select('*').eq('workspace_id', ws.id);
      if (cancelled) return;
      setLoading(false);
      if (res.error) { toast.push(res.error.message); return; }
      const map = {};
      (res.data || []).forEach(a => { map[a.kind] = a; });
      setByKind(map);
    })();
    return () => { cancelled = true; };
  }, [ws?.id, toast]);

  const updateOne = (kind, patch) => {
    setByKind(prev => Object.assign({}, prev, { [kind]: Object.assign({}, prev[kind] || {}, patch) }));
  };

  const saveOne = async (kind, patch) => {
    const row = byKind[kind];
    if (!row) return;
    const res = await SB.from('automations').update(patch).eq('id', row.id);
    if (res.error) { toast.push("Couldn't save: " + res.error.message); return false; }
    return true;
  };

  const toggleEnabled = async (kind) => {
    const row = byKind[kind];
    if (!row) return;
    const next = !row.enabled;
    updateOne(kind, { enabled: next });
    const ok = await saveOne(kind, { enabled: next });
    if (ok) toast.push(next ? "Automation enabled" : "Automation disabled");
  };

  const activeCount = Object.values(byKind).filter(a => a.enabled).length;
  const editing = editKind ? byKind[editKind] : null;

  return (
    <div className="px-5 lg:px-7 py-7 max-w-[1100px] mx-auto">
      <PageHeader
        eyebrow="Communication"
        title="Automations"
        subtitle="Emails sent automatically when bookings change. Edit the wording to match your brand."
      />

      <div className="grid grid-cols-2 md:grid-cols-3 gap-3 mb-6">
        <StatCard label="Active" value={activeCount} hint={`of ${AUTOMATION_DEFS.length}`} />
        <StatCard label="Sender" value="Resend" hint="onboarding@resend.dev" />
        <StatCard label="To customers" value={AUTOMATION_DEFS.filter(d => d.to === "customer").length} hint="Plus 1 owner alert" />
      </div>

      {loading ? (
        <div className="py-16 text-center text-[12.5px] text-ink/50">Loading templates…</div>
      ) : (
        <div className="rounded-lg border border-ink/[0.06] bg-ink/[0.015] overflow-hidden">
          {AUTOMATION_DEFS.map((def, i) => {
            const row = byKind[def.kind];
            if (!row) {
              return (
                <div key={def.kind} className={`px-5 py-4 flex items-center gap-4 ${i ? "border-t border-ink/[0.06]" : ""} bg-white`}>
                  <div className="h-9 w-9 rounded-md grid place-items-center bg-warn/15 text-warn flex-shrink-0">
                    <Icon name="alert-triangle" size={14} />
                  </div>
                  <div className="flex-1">
                    <div className="text-[14px] font-medium">{def.name}</div>
                    <div className="text-[12px] text-ink/55">Template missing — re-seed via Supabase SQL editor.</div>
                  </div>
                </div>
              );
            }
            return (
              <div key={def.kind} className={`px-5 py-4 flex items-center gap-4 ${i ? "border-t border-ink/[0.06]" : ""} hover:bg-white`}>
                <div className={`h-9 w-9 rounded-md grid place-items-center flex-shrink-0 ${row.enabled ? "bg-accent/15 text-[#3D7BB0]" : "bg-white text-ink/50"}`}>
                  <Icon name={def.to === "owner" ? "bell" : "send"} size={14} />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2.5 flex-wrap">
                    <div className="text-[14px] font-medium">{def.name}</div>
                    <Badge tone={def.to === "owner" ? "warn" : "accent"}>{def.to === "owner" ? "To owner" : "To customer"}</Badge>
                    {!row.enabled && <Badge tone="neutral">Off</Badge>}
                  </div>
                  <div className="text-[12px] text-ink/55 mt-0.5 truncate">Subject: <span className="text-ink/80">{row.subject}</span></div>
                  <div className="text-[11.5px] text-ink/45 mt-0.5">{def.desc}</div>
                </div>
                <div className="flex items-center gap-3 flex-shrink-0">
                  <Toggle checked={row.enabled} onChange={() => toggleEnabled(def.kind)} size="sm" />
                  <Button size="sm" variant="secondary" icon="pencil" onClick={() => setEditKind(def.kind)}>Edit</Button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {editing && (
        <AutomationEditor
          row={editing}
          def={AUTOMATION_DEFS.find(d => d.kind === editKind)}
          onClose={() => setEditKind(null)}
          onSave={async (next) => {
            updateOne(editKind, next);
            const ok = await saveOne(editKind, { subject: next.subject, body: next.body, enabled: next.enabled });
            if (ok) { toast.push("Template saved"); setEditKind(null); }
          }}
        />
      )}
    </div>
  );
}

function AutomationEditor({ row, def, onClose, onSave }) {
  const [subject, setSubject] = useState(row.subject);
  const [body, setBody] = useState(row.body);
  const [enabled, setEnabled] = useState(row.enabled);
  const [busy, setBusy] = useState(false);

  // Sample variables for the preview.
  const sample = {
    first_name: "Marcus", customer: "Marcus Whitfield",
    date: "Friday, May 30", time: "9:30 AM",
    service: "Schedule Service", business: "Your Business",
    proposed_date: "Saturday, June 1", proposed_time: "11:00 AM",
    event: "Backcountry Riding Clinic"
  };
  const renderSample = (text) => text.replace(/\{\{(\w+)\}\}/g, (_, k) => sample[k] !== undefined ? sample[k] : `{{${k}}}`);

  return (
    <Drawer
      open={true}
      onClose={onClose}
      title={def?.name || "Template"}
      subtitle={def?.to === "owner" ? "To owner" : "To customer"}
      width={620}
      actions={
        <>
          <Button variant="ghost" onClick={onClose} disabled={busy}>Cancel</Button>
          <Button icon="check" onClick={async () => { setBusy(true); await onSave({ subject, body, enabled }); setBusy(false); }} disabled={busy}>Save</Button>
        </>
      }
    >
      <div className="flex flex-col gap-4">
        <Field label="Status">
          <Toggle checked={enabled} onChange={setEnabled} label={enabled ? "Enabled" : "Disabled"} />
        </Field>
        <Field label="Subject line">
          <Input value={subject} onChange={(e) => setSubject(e.target.value)} />
        </Field>
        <Field label="Message">
          <Textarea rows={8} value={body} onChange={(e) => setBody(e.target.value)} />
        </Field>

        <div>
          <div className="text-[11px] uppercase tracking-[0.1em] text-ink/45 mb-2">Variables you can use</div>
          <div className="flex flex-wrap gap-1.5">
            {TEMPLATE_VARS.map(v => (
              <span key={v} className="font-mono text-[11px] px-2 py-1 rounded-md bg-ink/[0.04] border border-ink/[0.06]">{v}</span>
            ))}
          </div>
        </div>

        <div className="rounded-md border border-ink/[0.08] bg-ink text-white p-4">
          <div className="text-[11px] uppercase tracking-[0.1em] text-white/45 mb-2">Preview · with sample data</div>
          <div className="font-medium">{renderSample(subject)}</div>
          <div className="mt-2 text-white/75 whitespace-pre-line text-[13px]">{renderSample(body)}</div>
        </div>
      </div>
    </Drawer>
  );
}

// ── Settings ─────────────────────────────────────────────────────────────
const SETTINGS_TABS = [
  { id: "profile",  label: "Business profile", icon: "building" },
  { id: "hours",    label: "Availability",     icon: "clock" },
  { id: "team",     label: "Team members",     icon: "users" },
  { id: "notif",    label: "Notifications",    icon: "mail" },
  { id: "danger",   label: "Danger zone",      icon: "shield" }
];

function SettingsPage() {
  const [tab, setTab] = useState("profile");

  return (
    <div className="px-5 lg:px-7 py-7 max-w-[1300px] mx-auto">
      <PageHeader eyebrow="Workspace" title="Settings" subtitle="Manage your business profile, hours, and team." />

      <div className="grid lg:grid-cols-[220px_1fr] gap-7">
        <aside className="flex lg:flex-col gap-1 overflow-x-auto lg:overflow-visible">
          {SETTINGS_TABS.map((t) => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`flex items-center gap-2.5 px-3 py-2 rounded-md text-[13px] whitespace-nowrap transition ${
                tab === t.id ? "bg-ink text-white" : "text-ink/65 hover:text-ink hover:bg-white"
              }`}
            >
              <Icon name={t.icon} size={14} className={tab === t.id ? "text-white/75" : "text-ink/60"} />
              {t.label}
            </button>
          ))}
        </aside>

        <div className="max-w-2xl">
          {tab === "profile" && <ProfileSettings />}
          {tab === "hours"   && <HoursSettings />}
          {tab === "team"    && <TeamSettings />}
          {tab === "notif"   && <NotifSettings />}
          {tab === "danger"  && <DangerSettings />}
        </div>
      </div>
    </div>
  );
}

function SettingsSection({ title, subtitle, children, action }) {
  return (
    <section className="rounded-lg border border-ink/[0.06] bg-white">
      <header className="px-5 py-4 border-b border-ink/[0.06] flex items-center justify-between gap-3">
        <div>
          <h3 className="font-display text-[20px] tracking-tight leading-tight">{title}</h3>
          {subtitle && <div className="text-[12.5px] text-ink/55 mt-0.5">{subtitle}</div>}
        </div>
        {action}
      </header>
      <div className="p-5">{children}</div>
    </section>
  );
}

function ProfileSettings() {
  const auth = useAuth();
  const ws = auth.currentWorkspace;
  const toast = useToast();
  const [name, setName] = useState("");
  const [industry, setIndustry] = useState("other");
  const [timezone, setTimezone] = useState("Europe/Brussels");
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (ws) {
      setName(ws.name || "");
      setIndustry(ws.industry || "other");
      setTimezone(ws.timezone || "Europe/Brussels");
    }
  }, [ws?.id]);

  if (!ws) return null;

  const dirty = name !== ws.name || industry !== ws.industry || timezone !== ws.timezone;

  const save = async () => {
    setBusy(true);
    const res = await SB.from('workspaces').update({ name, industry, timezone }).eq('id', ws.id).select().single();
    setBusy(false);
    if (res.error) { toast.push("Couldn't save: " + res.error.message); return; }
    auth.setCurrentWorkspace(res.data);
    toast.push("Profile saved");
  };

  return (
    <SettingsSection title="Business profile" subtitle="The name and slug shown to customers and on emails.">
      <div className="grid sm:grid-cols-2 gap-4">
        <Field label="Business name" required>
          <Input value={name} onChange={(e) => setName(e.target.value)} />
        </Field>
        <Field label="Industry">
          <Select value={industry} onChange={(e) => setIndustry(e.target.value)}>
            <option value="powersports">Powersports</option>
            <option value="restaurant">Restaurant</option>
            <option value="dentist">Dentist</option>
            <option value="other">Other</option>
          </Select>
        </Field>
        <Field label="Public slug" hint="Used in your public booking URL. Editing it breaks any link that's already out there.">
          <Input value={ws.slug} readOnly className="!opacity-60" />
        </Field>
        <Field label="Timezone" hint="All booking times shown to you display in this zone.">
          <Select value={timezone} onChange={(e) => setTimezone(e.target.value)}>
            {["Europe/Brussels","Europe/Amsterdam","Europe/Paris","Europe/London","Europe/Madrid","America/New_York","America/Denver","America/Los_Angeles","America/Chicago","Asia/Tokyo","Asia/Singapore","Australia/Sydney"].map(tz => <option key={tz} value={tz}>{tz}</option>)}
          </Select>
        </Field>
      </div>
      <div className="mt-5 flex items-center justify-end gap-2">
        <Button variant="ghost" disabled={!dirty || busy} onClick={() => { setName(ws.name); setIndustry(ws.industry); setTimezone(ws.timezone); }}>Discard</Button>
        <Button icon="check" disabled={!dirty || busy} onClick={save}>{busy ? "Saving…" : "Save changes"}</Button>
      </div>
    </SettingsSection>
  );
}

const DAY_KEYS = ["mon","tue","wed","thu","fri","sat","sun"];
const DAY_LABELS = { mon: "Monday", tue: "Tuesday", wed: "Wednesday", thu: "Thursday", fri: "Friday", sat: "Saturday", sun: "Sunday" };

function HoursSettings() {
  const auth = useAuth();
  const ws = auth.currentWorkspace;
  const toast = useToast();
  const [hours, setHours] = useState({});
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!ws) return;
    setHours(ws.hours || {});
  }, [ws?.id]);

  if (!ws) return null;

  const setDay = (key, value) => setHours(prev => Object.assign({}, prev, { [key]: value }));
  const closed = (key) => Array.isArray(hours[key]) && hours[key][0] === "closed";
  const open  = (key) => Array.isArray(hours[key]) && hours[key][0] !== "closed" ? hours[key][0] : "09:00";
  const close = (key) => Array.isArray(hours[key]) && hours[key][0] !== "closed" ? (hours[key][1] || "17:00") : "17:00";

  const toggleClosed = (key) => setDay(key, closed(key) ? ["09:00","17:00"] : ["closed"]);

  const save = async () => {
    setBusy(true);
    const res = await SB.from('workspaces').update({ hours }).eq('id', ws.id).select().single();
    setBusy(false);
    if (res.error) { toast.push("Couldn't save: " + res.error.message); return; }
    auth.setCurrentWorkspace(res.data);
    toast.push("Hours saved");
  };

  const dirty = JSON.stringify(hours) !== JSON.stringify(ws.hours || {});

  return (
    <SettingsSection title="Availability" subtitle="Default business hours used to generate booking slots.">
      <div className="rounded-md border border-ink/[0.06] divide-y divide-ink/[0.06] overflow-hidden">
        {DAY_KEYS.map((k) => (
          <div key={k} className="flex items-center gap-3 px-4 py-3">
            <span className="text-[13px] w-24">{DAY_LABELS[k]}</span>
            <Toggle checked={!closed(k)} onChange={() => toggleClosed(k)} size="sm" />
            {!closed(k) ? (
              <div className="flex items-center gap-2 ml-2">
                <input
                  type="time"
                  value={open(k)}
                  onChange={(e) => setDay(k, [e.target.value, close(k)])}
                  className="h-7 w-24 px-2 text-[12.5px] border border-ink/[0.10] rounded-md outline-none focus:border-ink/30"
                />
                <span className="text-ink/40">–</span>
                <input
                  type="time"
                  value={close(k)}
                  onChange={(e) => setDay(k, [open(k), e.target.value])}
                  className="h-7 w-24 px-2 text-[12.5px] border border-ink/[0.10] rounded-md outline-none focus:border-ink/30"
                />
              </div>
            ) : (
              <span className="text-[12.5px] text-ink/40 ml-2">Closed</span>
            )}
          </div>
        ))}
      </div>
      <div className="mt-5 flex items-center justify-end gap-2">
        <Button variant="ghost" disabled={!dirty || busy} onClick={() => setHours(ws.hours || {})}>Discard</Button>
        <Button icon="check" disabled={!dirty || busy} onClick={save}>{busy ? "Saving…" : "Save hours"}</Button>
      </div>
    </SettingsSection>
  );
}

function TeamSettings() {
  const auth = useAuth();
  const ws = auth.currentWorkspace;
  const toast = useToast();
  const [members, setMembers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!ws?.id) { setLoading(false); return; }
    let cancelled = false;
    (async () => {
      const res = await SB.from('workspace_members').select('*').eq('workspace_id', ws.id).order('created_at');
      if (cancelled) return;
      setLoading(false);
      if (res.error) { toast.push(res.error.message); return; }
      setMembers(res.data || []);
    })();
    return () => { cancelled = true; };
  }, [ws?.id, toast]);

  return (
    <SettingsSection
      title="Team members"
      subtitle="People who can sign in and manage this workspace."
      action={<Button size="sm" icon="user-plus" disabled title="Invite flow coming soon">Invite</Button>}
    >
      {loading ? (
        <div className="py-6 text-center text-[12.5px] text-ink/50">Loading…</div>
      ) : members.length === 0 ? (
        <div className="rounded-md border border-dashed border-ink/[0.12] py-6 text-center">
          <div className="text-[13px]">No team members yet</div>
          <p className="text-[11.5px] text-ink/55 mt-1">{auth.isAgencyAdmin ? "Agency admins (Vale staff) can manage this workspace without being members." : "Ask your agency to add team members."}</p>
        </div>
      ) : (
        <div className="rounded-md border border-ink/[0.06] divide-y divide-ink/[0.06]">
          {members.map(m => (
            <div key={m.id} className="px-4 py-3 flex items-center gap-3">
              <Avatar name={m.name} size={32} />
              <div className="flex-1 min-w-0">
                <div className="text-[13px] font-medium">{m.name}</div>
                <div className="text-[11.5px] text-ink/55 truncate capitalize">{m.role}</div>
              </div>
              <Badge tone={m.role === "owner" ? "accent" : "neutral"}>{m.role}</Badge>
            </div>
          ))}
        </div>
      )}
      <p className="mt-4 text-[11.5px] text-ink/45">Invite flow + permission editing land in a later session. For now, members can be added via the Supabase dashboard if needed.</p>
    </SettingsSection>
  );
}

function NotifSettings() {
  return (
    <SettingsSection title="Email notifications" subtitle="What you receive personally — separate from customer-facing automations.">
      <div className="rounded-md border border-ink/[0.06] divide-y divide-ink/[0.06] overflow-hidden">
        {[
          ["New booking received", true],
          ["Booking cancelled by customer", true],
          ["Daily summary at 8:00 AM", false],
          ["Weekly digest on Mondays", true]
        ].map(([label, on]) => (
          <div key={label} className="flex items-center justify-between px-4 py-3">
            <span className="text-[13px]">{label}</span>
            <LocalToggle defaultChecked={on} size="sm" />
          </div>
        ))}
      </div>
      <p className="mt-4 text-[11.5px] text-ink/45">These toggles don't persist yet — they're UI placeholders. Wired in a later session.</p>
    </SettingsSection>
  );
}

function DangerSettings() {
  const auth = useAuth();
  const ws = auth.currentWorkspace;
  const toast = useToast();

  const deleteWorkspace = async () => {
    if (!ws) return;
    const confirmed = window.prompt(`Type the workspace name "${ws.name}" to confirm deletion. This permanently removes all bookings, customers, forms, and events.`);
    if (confirmed !== ws.name) { if (confirmed !== null) toast.push("Name didn't match — nothing deleted"); return; }
    const res = await SB.from('workspaces').delete().eq('id', ws.id);
    if (res.error) { toast.push("Couldn't delete: " + res.error.message); return; }
    auth.setCurrentWorkspace(null);
    window.location.hash = "#/agency/clients";
    toast.push(`Workspace "${ws.name}" deleted`);
  };

  return (
    <SettingsSection title="Danger zone" subtitle="Permanent actions.">
      <div className="rounded-md border border-danger/30 bg-danger/[0.04] p-4">
        <div className="text-[13.5px] font-medium">Delete this workspace</div>
        <p className="text-[12.5px] text-ink/65 mt-1">
          Removes the workspace and everything in it — bookings, customers, forms, automations, activity. This can't be undone.
        </p>
        <div className="mt-4">
          <Button variant="secondary" icon="trash-2" onClick={deleteWorkspace}>Delete workspace…</Button>
        </div>
      </div>
    </SettingsSection>
  );
}

Object.assign(window, { WebsiteInstallPage, AutomationsPage, SettingsPage });
