// Agency Admin — Clients page (real Supabase data)
const INDUSTRY_OPTIONS = [
  { value: "powersports", label: "Powersports" },
  { value: "restaurant",  label: "Restaurant" },
  { value: "dentist",     label: "Dentist" },
  { value: "other",       label: "Other" }
];

function slugify(s) {
  return (s || "")
    .toLowerCase()
    .normalize("NFKD").replace(/[̀-ͯ]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 60);
}

function AgencyClientsPage() {
  const [workspaces, setWorkspaces] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [query, setQuery] = useState("");
  const [selected, setSelected] = useState(null);
  const [showNew, setShowNew] = useState(false);
  const toast = useToast();
  const auth = useAuth();
  const navigate = ReactRouterDOM.useNavigate();
  const openWs = (ws) => {
    if (!ws) return;
    auth.setCurrentWorkspace(ws);
    navigate("/app/dashboard");
  };

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    const res = await SB.from('workspaces').select('*').order('created_at', { ascending: false });
    setLoading(false);
    if (res.error) { setError(res.error.message); return; }
    setWorkspaces(res.data || []);
  }, []);

  useEffect(() => { load(); }, [load]);

  const filtered = workspaces.filter((w) => {
    if (!query) return true;
    const haystack = (w.name + " " + w.slug + " " + (w.industry || "")).toLowerCase();
    return haystack.includes(query.toLowerCase());
  });

  const handleCreated = (ws) => {
    setWorkspaces([ws].concat(workspaces));
    setShowNew(false);
    toast.push(`Created “${ws.name}”`);
  };

  return (
    <div className="max-w-[1400px] mx-auto px-6 lg:px-10 py-9">
      <PageHeader
        eyebrow="Vale agency · admin console"
        title="Clients"
        subtitle="Every workspace Vale manages."
        actions={<Button icon="plus" onClick={() => setShowNew(true)}>Create workspace</Button>}
      />

      <div className="grid grid-cols-2 md:grid-cols-3 gap-3 mb-6">
        <StatCard label="Workspaces" value={workspaces.length} hint={workspaces.length === 1 ? "1 active" : `${workspaces.length} active`} />
        <StatCard label="Powersports" value={workspaces.filter(w => w.industry === "powersports").length} hint="Of total" />
        <StatCard label="Other industries" value={workspaces.filter(w => w.industry !== "powersports").length} hint="Restaurants, dentists, …" />
      </div>

      {/* Toolbar */}
      <div className="flex flex-wrap items-center gap-3 mb-4">
        <div className="flex items-center gap-2 bg-ink/[0.02] border border-ink/[0.06] rounded-md px-2.5 h-9 w-full sm:w-80">
          <Icon name="search" size={13} className="text-ink/40" />
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search clients" className="bg-transparent flex-1 text-[13px] placeholder-ink/35 outline-none" />
        </div>
        <div className="ml-auto text-[12px] text-ink/55">{filtered.length} of {workspaces.length}</div>
      </div>

      {loading ? (
        <div className="py-16 text-center text-[12.5px] text-ink/50">Loading workspaces…</div>
      ) : error ? (
        <div className="py-16 text-center text-[12.5px] text-danger">Couldn't load workspaces: {error}</div>
      ) : workspaces.length === 0 ? (
        <div className="rounded-lg border border-dashed border-ink/[0.12] bg-white p-12 text-center">
          <div className="font-display text-[20px] mb-1">No workspaces yet</div>
          <p className="text-[13px] text-ink/55 mb-5 max-w-md mx-auto">
            Create one for Vale itself and one for each client you manage. Each workspace has its own customers, bookings, forms, and emails.
          </p>
          <Button icon="plus" onClick={() => setShowNew(true)}>Create your first workspace</Button>
        </div>
      ) : (
        <div className="rounded-lg border border-ink/[0.06] bg-ink/[0.015] overflow-hidden">
          <table className="w-full text-[13px]">
            <thead className="text-[11px] uppercase tracking-[0.08em] text-ink/45 bg-white">
              <tr className="border-b border-ink/[0.06]">
                <th className="text-left font-medium px-5 py-3">Workspace</th>
                <th className="text-left font-medium px-2 py-3 hidden md:table-cell">Industry</th>
                <th className="text-left font-medium px-2 py-3 hidden md:table-cell">Created</th>
                <th className="px-5 py-3 text-right font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(w => (
                <tr key={w.id} onClick={() => setSelected(w)} className="border-b border-ink/[0.04] hover:bg-white cursor-pointer">
                  <td className="px-5 py-3">
                    <div className="flex items-center gap-3">
                      <div className="h-9 w-9 rounded-md bg-ink/[0.04] grid place-items-center text-[11px] uppercase tracking-wide">
                        {w.name.split(" ").filter(Boolean).slice(0,2).map(s => s[0]).join("")}
                      </div>
                      <div className="min-w-0">
                        <div className="font-medium">{w.name}</div>
                        <div className="text-[11.5px] text-ink/55 truncate font-mono">/{w.slug}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-2 py-3 hidden md:table-cell">
                    <Badge tone="neutral">{w.industry || "other"}</Badge>
                  </td>
                  <td className="px-2 py-3 text-ink/65 hidden md:table-cell">{fmt(w.created_at, "MMM d, yyyy")}</td>
                  <td className="px-5 py-3 text-right">
                    <button
                      title="Open workspace"
                      className="p-1.5 rounded hover:bg-ink/[0.04] text-ink/65 hover:text-ink"
                      onClick={(e) => { e.stopPropagation(); openWs(w); }}
                    >
                      <Icon name="log-in" size={13} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <Drawer
        open={!!selected}
        onClose={() => setSelected(null)}
        title={selected?.name}
        subtitle="Client workspace"
        width={520}
        actions={selected && (
          <Button icon="log-in" onClick={() => openWs(selected)}>Open workspace</Button>
        )}
      >
        {selected && (
          <div>
            <div className="flex items-center gap-3 pb-5 border-b border-ink/[0.06]">
              <div className="h-12 w-12 rounded-md bg-ink/[0.04] grid place-items-center text-[14px] uppercase">
                {selected.name.split(" ").filter(Boolean).slice(0,2).map(s => s[0]).join("")}
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-[15px]">{selected.name}</div>
                <div className="text-[12.5px] text-ink/55 font-mono">/{selected.slug}</div>
              </div>
              <Badge tone="neutral">{selected.industry || "other"}</Badge>
            </div>

            <dl className="grid grid-cols-2 gap-y-4 gap-x-6 pt-5 text-[13px]">
              <DL label="Created">{fmt(selected.created_at, "MMM d, yyyy · h:mma")}</DL>
              <DL label="Timezone">{selected.timezone || "Europe/Brussels"}</DL>
              <DL label="Industry">{selected.industry || "other"}</DL>
              <DL label="Workspace ID"><span className="font-mono text-[11px]">{selected.id}</span></DL>
            </dl>

            <div className="mt-6">
              <div className="text-[11px] uppercase tracking-[0.1em] text-ink/45 mb-2">Public booking URL</div>
              <pre className="rounded-md border border-ink/[0.06] bg-ink p-3 font-mono text-[11.5px] text-white/85 overflow-x-auto">
{`${window.location.origin}/#/public/${selected.slug}`}
              </pre>
            </div>
          </div>
        )}
      </Drawer>

      <NewWorkspaceModal open={showNew} onClose={() => setShowNew(false)} onCreated={handleCreated} />
    </div>
  );
}

// New workspace modal — name + slug + industry. Inserts into Supabase, then
// seeds the default email automations for the new workspace.
function NewWorkspaceModal({ open, onClose, onCreated }) {
  const [name, setName] = useState("");
  const [slug, setSlug] = useState("");
  const [slugTouched, setSlugTouched] = useState(false);
  const [industry, setIndustry] = useState("powersports");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  // Auto-derive slug from name unless the user has typed in the slug field manually.
  useEffect(() => {
    if (!slugTouched) setSlug(slugify(name));
  }, [name, slugTouched]);

  // Reset state every time the modal opens.
  useEffect(() => {
    if (open) {
      setName(""); setSlug(""); setSlugTouched(false);
      setIndustry("powersports"); setBusy(false); setError(null);
    }
  }, [open]);

  const canSubmit = name.trim().length >= 2 && /^[a-z0-9-]{2,}$/.test(slug) && !busy;

  const submit = async () => {
    setBusy(true); setError(null);
    const insert = await SB.from('workspaces')
      .insert({ name: name.trim(), slug: slug.trim(), industry })
      .select()
      .single();
    if (insert.error) {
      setBusy(false);
      setError(insert.error.code === '23505'
        ? `Slug “${slug}” is already taken — pick another.`
        : insert.error.message);
      return;
    }
    // Seed the default email templates for this workspace. Non-fatal if it fails.
    const seed = await SB.rpc('seed_default_automations', { p_workspace: insert.data.id });
    if (seed.error) console.warn('seed_default_automations failed', seed.error);
    setBusy(false);
    onCreated(insert.data);
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Create workspace"
      subtitle="One workspace per business. Each has its own data, totally isolated."
      width={520}
      actions={
        <>
          <Button variant="ghost" onClick={onClose} disabled={busy}>Cancel</Button>
          <Button icon="check" onClick={submit} disabled={!canSubmit}>
            {busy ? "Creating…" : "Create workspace"}
          </Button>
        </>
      }
    >
      <div className="flex flex-col gap-4">
        <Field label="Business name" required>
          <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Van de Veire Powersports" autoFocus />
        </Field>
        <Field
          label="URL slug"
          required
          hint={
            slug
              ? <>Public booking URL: <span className="font-mono">/public/{slug}</span></>
              : "Letters, numbers, dashes only"
          }
        >
          <Input
            value={slug}
            onChange={(e) => { setSlug(e.target.value.toLowerCase()); setSlugTouched(true); }}
            placeholder="van-de-veire-powersports"
          />
        </Field>
        <Field label="Industry" hint="Tunes the booking-form templates we'll offer.">
          <Select value={industry} onChange={(e) => setIndustry(e.target.value)}>
            {INDUSTRY_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </Select>
        </Field>
        {error && (
          <div className="text-[12px] text-danger bg-danger/[0.06] border border-danger/15 rounded-md px-3 py-2">{error}</div>
        )}
      </div>
    </Modal>
  );
}

function AgencyTemplatesPage() {
  const templates = [
    { name: "Granite", desc: "Editorial · serif · restrained", clients: 3, accent: "#3D7BB0" },
    { name: "Linen",   desc: "Warm · airy · hospitality",      clients: 2, accent: "#B07A2A" },
    { name: "Pearl",   desc: "Medical · trustworthy · clean",  clients: 2, accent: "#5F8D8C" },
    { name: "Slate",   desc: "Bold · contrasty · outdoors",    clients: 1, accent: "#274E70" }
  ];
  return (
    <div className="max-w-[1400px] mx-auto px-6 lg:px-10 py-9">
      <PageHeader eyebrow="Design presets" title="Templates" subtitle="Locked design systems used across client booking cards." actions={<Button icon="plus">New template</Button>} />
      <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {templates.map(t => (
          <div key={t.name} className="rounded-lg border border-ink/[0.06] bg-white overflow-hidden">
            <div className="h-32 placeholder-stripes border-b border-ink/[0.06] flex items-end p-4" style={{ background: `linear-gradient(135deg, ${t.accent}22, transparent), repeating-linear-gradient(45deg, rgba(255,255,255,0.04) 0 1px, transparent 1px 8px)` }}>
              <div className="font-display text-[26px] leading-none">{t.name}</div>
            </div>
            <div className="p-4">
              <div className="text-[12.5px] text-ink/65">{t.desc}</div>
              <div className="mt-3 flex items-center justify-between">
                <span className="text-[11.5px] text-ink/45">{t.clients} {t.clients === 1 ? "client" : "clients"}</span>
                <button className="text-[12px] text-ink/75 hover:text-ink">Edit preset</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AgencyEmbedPage() {
  return (
    <div className="max-w-[1100px] mx-auto px-6 lg:px-10 py-9">
      <PageHeader eyebrow="Distribution" title="Embed settings" subtitle="Global config for the loader script Vale drops onto client sites." />
      <div className="grid lg:grid-cols-2 gap-4">
        <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">Loader version</div>
          <div className="flex items-center gap-2 mb-4">
            <Badge tone="ok" dot>2.4.1 stable</Badge>
            <span className="text-[12px] text-ink/55">Released May 12</span>
          </div>
          <div className="rounded-md border border-ink/[0.06] divide-y divide-ink/[0.06] overflow-hidden">
            <SettingRow label="Auto-update clients" hint="Push patch releases without redeploy"><LocalToggle defaultChecked={true} size="sm" /></SettingRow>
            <SettingRow label="Async loading" hint="Don't block page render"><LocalToggle defaultChecked={true} size="sm" /></SettingRow>
            <SettingRow label="Subresource integrity" hint="Sign loader with SHA-384"><LocalToggle defaultChecked={true} size="sm" /></SettingRow>
          </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-3">Default modules</div>
          <p className="text-[12.5px] text-ink/55 mb-3">Enabled by default when creating a new client.</p>
          <div className="flex flex-col gap-2">
            {["Bookings","Events","Customers","Automations"].map(m => (
              <label key={m} className="flex items-center justify-between px-3 py-2 rounded border border-ink/[0.06] bg-white">
                <span className="text-[13px]">{m}</span>
                <LocalToggle defaultChecked={m !== "Automations"} size="sm" />
              </label>
            ))}
          </div>
        </div>

        <div className="lg:col-span-2 rounded-lg border border-ink/[0.06] bg-white p-5">
          <div className="text-[11px] uppercase tracking-[0.1em] text-ink/50 mb-3">Master embed snippet</div>
          <pre className="rounded-md border border-ink/[0.06] bg-ink p-3 font-mono text-[12px] text-white/90 overflow-x-auto">
{`<script async src="https://embed.vale.co/v2.4/loader.js"
  data-workspace="ws_{{client_id}}"
  data-template="{{template}}"
  data-modules="{{modules}}"
  integrity="sha384-..."></script>

<!-- Drop anywhere the booking card should render -->
<div data-vale-booking></div>`}
          </pre>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AgencyClientsPage, AgencyTemplatesPage, AgencyEmbedPage });
