import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { PageShell } from "@/components/page-shell";
import { toolSeo } from "@/lib/tool-seo";
import { supabase } from "@/integrations/supabase/client";
import { MessageSquare, Send, Bot, User as UserIcon, Copy, Trash2, Check, BarChart3 } from "lucide-react";

export const Route = createFileRoute("/tools/chatbot")({
  head: () => toolSeo({
    path: "/tools/chatbot",
    title: "AI Chatbot Builder — Add live customer chat to your website | Gatavase AI",
    shortTitle: "AI Chatbot Builder",
    description:
      "Design, brand and embed a Gatavase AI chatbot on your website in minutes. Configure a welcome message, tone, knowledge, widget position, size, title and logo, then paste one snippet of HTML into your site to let customers chat instantly — 24/7 answers, lead capture and support handled by AI. Build your chatbot as a guest with drafts saved in your browser, try the live sample without signing up, and only share your name and email when you publish an embed. Built for Ugandan businesses, agencies and creators who want fast, friendly customer conversations at scale, in any language your visitors speak.",
    ogDescription: "Configure a branded AI chatbot as a guest and embed it on your website in minutes — no account needed until you publish.",
    category: "BusinessApplication",
  }),
  component: ChatbotPage,
});

type Msg = { role: "user" | "assistant"; content: string };

type WidgetPosition = "bottom-right" | "bottom-left" | "top-right" | "top-left";
type WidgetSize = "small" | "medium" | "large" | "full";

type ChatbotDraft = {
  name: string;
  welcome_message: string;
  system_prompt: string;
  brand_color: string;
  is_active: boolean;
  widget_position: WidgetPosition;
  widget_size: WidgetSize;
  widget_title: string;
  logo_url: string | null;
  launcher_label: string;
};
type Chatbot = ChatbotDraft & { id: string };

const DRAFT_KEY = "gatavase.chatbot.draft.v1";

const DEMO_SYSTEM =
  "You are 'Kato', the friendly demo chatbot for a boutique coffee shop in Kampala called 'Nile Roasters'. Answer briefly (1-3 sentences), warmly, and in the visitor's language. Menu highlights: single-origin Bugisu espresso, cold brew, chai latte. Hours: Mon-Sat 7am-8pm. If asked things you don't know, invite them to visit the shop.";

const DEFAULT_CFG: ChatbotDraft = {
  name: "My Website Assistant",
  welcome_message: "Hi 👋 How can I help you today?",
  system_prompt:
    "You are a friendly, concise customer support assistant. Answer questions about our products and services in 1-3 sentences. If you don't know something, offer to connect the visitor with a human via email.",
  brand_color: "#7c3aed",
  is_active: true,
  widget_position: "bottom-right",
  widget_size: "medium",
  widget_title: "Chat with us",
  logo_url: null,
  launcher_label: "💬",
};

function loadDraft(): ChatbotDraft {
  if (typeof window === "undefined") return DEFAULT_CFG;
  try {
    const raw = window.localStorage.getItem(DRAFT_KEY);
    if (!raw) return DEFAULT_CFG;
    return { ...DEFAULT_CFG, ...(JSON.parse(raw) as Partial<ChatbotDraft>) };
  } catch {
    return DEFAULT_CFG;
  }
}

function ChatbotPage() {
  const [tab, setTab] = useState<"demo" | "configure">("demo");
  const [email, setEmail] = useState<string | null>(null);
  const [loadingUser, setLoadingUser] = useState(true);

  useEffect(() => {
    void (async () => {
      const { data } = await supabase.auth.getUser();
      setEmail(data.user?.is_anonymous ? null : data.user?.email ?? null);
      setLoadingUser(false);
    })();
    const { data: sub } = supabase.auth.onAuthStateChange((_e, session) => {
      setEmail(session?.user?.is_anonymous ? null : session?.user?.email ?? null);
    });
    return () => sub.subscription.unsubscribe();
  }, []);

  return (
    <PageShell
      eyebrow="Customer engagement"
      title="AI Chatbot Builder"
      lead="Try the live demo, then configure your own chatbot as a guest — your draft is saved in this browser. We only ask for your name and email when you publish an embed."
    >
      <div className="mb-6 inline-flex rounded-xl border border-border bg-card/50 p-1">
        <button
          className={`rounded-lg px-4 py-2 text-sm font-medium transition ${tab === "demo" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground"}`}
          onClick={() => setTab("demo")}
        >
          <MessageSquare className="mr-1.5 inline h-4 w-4" /> Live sample
        </button>
        <button
          className={`rounded-lg px-4 py-2 text-sm font-medium transition ${tab === "configure" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground"}`}
          onClick={() => setTab("configure")}
        >
          <Bot className="mr-1.5 inline h-4 w-4" /> Configure yours
        </button>
      </div>

      {tab === "demo" && <DemoChat />}
      {tab === "configure" && (loadingUser ? <div className="text-sm text-muted-foreground">Loading…</div> : <ConfigurePanel ownerEmail={email} />)}
    </PageShell>
  );
}

/* ---------------- Demo chat ---------------- */

function DemoChat() {
  return (
    <div className="glow-card rounded-2xl p-6">
      <div className="mb-4 flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-xl" style={{ background: "#7c3aed" }}>
          <Bot className="h-5 w-5 text-white" />
        </div>
        <div>
          <div className="font-display font-semibold">Nile Roasters — Sample chatbot</div>
          <div className="text-xs text-muted-foreground">Live AI reply · no sign-up needed</div>
        </div>
      </div>
      <ChatWindow brandColor="#7c3aed" welcome="Karibu! I'm Kato from Nile Roasters ☕ How can I help?" system={DEMO_SYSTEM} />
      <p className="mt-4 text-xs text-muted-foreground">
        This is a demo powered by Gatavase AI. Switch to “Configure yours” to build your own — no account needed until you publish.
      </p>
    </div>
  );
}

function newSessionId() {
  return `s_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
}

function ChatWindow({
  brandColor,
  welcome,
  system,
  configId,
  logoUrl,
  title,
}: { brandColor: string; welcome: string; system?: string; configId?: string; logoUrl?: string | null; title?: string }) {
  const [messages, setMessages] = useState<Msg[]>([{ role: "assistant", content: welcome }]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);
  const sessionRef = useRef(newSessionId());

  useEffect(() => {
    setMessages([{ role: "assistant", content: welcome }]);
    sessionRef.current = newSessionId();
  }, [welcome, configId]);

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
  }, [messages, busy]);

  async function send() {
    const text = input.trim();
    if (!text || busy) return;
    const next: Msg[] = [...messages, { role: "user", content: text }];
    setMessages(next);
    setInput("");
    setBusy(true);
    try {
      const res = await fetch("/api/public/chatbot/reply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          configId,
          system,
          hp: "",
          sessionId: sessionRef.current,
          messages: next.map((m) => ({ role: m.role, content: m.content })),
        }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json?.error ?? "Chat failed");
      setMessages((m) => [...m, { role: "assistant", content: json.reply || "…" }]);
    } catch (e) {
      setMessages((m) => [...m, { role: "assistant", content: `⚠️ ${e instanceof Error ? e.message : "Error"}` }]);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="overflow-hidden rounded-2xl border border-border bg-background/60">
      {title && (
        <div className="flex items-center gap-2 px-4 py-2.5 text-sm font-semibold text-white" style={{ background: brandColor }}>
          {logoUrl && <img src={logoUrl} alt="" className="h-5 w-5 rounded-full object-cover" />}
          {title}
        </div>
      )}
      <div ref={scrollRef} className="max-h-[420px] min-h-[260px] space-y-3 overflow-y-auto p-4">
        {messages.map((m, i) => (
          <div key={i} className={`flex gap-2 ${m.role === "user" ? "justify-end" : "justify-start"}`}>
            {m.role === "assistant" && (
              <div className="mt-1 flex h-7 w-7 shrink-0 items-center justify-center overflow-hidden rounded-full" style={{ background: brandColor }}>
                {logoUrl ? <img src={logoUrl} alt="" className="h-full w-full object-cover" /> : <Bot className="h-4 w-4 text-white" />}
              </div>
            )}
            <div
              className={`max-w-[75%] rounded-2xl px-3.5 py-2 text-sm ${m.role === "user" ? "text-primary-foreground" : "bg-card text-foreground"}`}
              style={m.role === "user" ? { background: brandColor } : undefined}
            >
              {m.content}
            </div>
            {m.role === "user" && (
              <div className="mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-muted">
                <UserIcon className="h-4 w-4 text-muted-foreground" />
              </div>
            )}
          </div>
        ))}
        {busy && <div className="text-xs text-muted-foreground">Typing…</div>}
      </div>
      <div className="flex gap-2 border-t border-border p-3">
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && send()}
          placeholder="Ask something…"
          className="flex-1 rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-primary"
        />
        <button
          onClick={send}
          disabled={busy || !input.trim()}
          className="rounded-lg px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
          style={{ background: brandColor }}
        >
          <Send className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
}

/* ---------------- Configure panel ---------------- */

function ConfigurePanel({ ownerEmail }: { ownerEmail: string | null }) {
  const [items, setItems] = useState<Chatbot[] | null>(null);
  const [editing, setEditing] = useState<Chatbot | ChatbotDraft>(() => loadDraft());
  const [err, setErr] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [copied, setCopied] = useState(false);
  const [publishOpen, setPublishOpen] = useState(false);

  const isSaved = "id" in editing;

  // Guest drafts persist in this browser only.
  useEffect(() => {
    if (isSaved || typeof window === "undefined") return;
    window.localStorage.setItem(DRAFT_KEY, JSON.stringify(editing));
  }, [editing, isSaved]);

  useEffect(() => {
    if (ownerEmail) void reload();
  }, [ownerEmail]);

  async function reload() {
    try {
      const { listMyChatbots } = await import("@/lib/chatbot.functions");
      setItems((await listMyChatbots()) as unknown as Chatbot[]);
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Failed to load");
    }
  }

  async function persist(contact?: { contact_name: string; contact_email: string }) {
    setSaving(true);
    setErr(null);
    try {
      const { saveChatbot } = await import("@/lib/chatbot.functions");
      const saved = await saveChatbot({ data: { ...editing, ...(contact ?? {}) } as never });
      setEditing(saved as unknown as Chatbot);
      if (typeof window !== "undefined") window.localStorage.removeItem(DRAFT_KEY);
      await reload();
      return true;
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Failed to save");
      return false;
    } finally {
      setSaving(false);
    }
  }

  async function remove(id: string) {
    if (!confirm("Delete this chatbot? The embed script will stop working.")) return;
    const { deleteChatbot } = await import("@/lib/chatbot.functions");
    await deleteChatbot({ data: { id } });
    if ("id" in editing && editing.id === id) setEditing(DEFAULT_CFG);
    await reload();
  }

  const origin = typeof window !== "undefined" ? window.location.origin : "";
  const embedSnippet = isSaved
    ? `<script src="${origin}/chatbot-widget.js" data-gatavase-chatbot="${(editing as Chatbot).id}" defer></script>`
    : "";

  return (
    <div className="grid gap-6 lg:grid-cols-[1fr,1fr]">
      <div className="space-y-4">
        <div className="glow-card rounded-2xl p-6">
          <div className="mb-4 flex items-center justify-between gap-3">
            <div>
              <div className="text-xs uppercase tracking-widest text-muted-foreground">{ownerEmail ? "Signed in as" : "Guest mode"}</div>
              <div className="text-sm font-semibold">{ownerEmail ?? "Draft saved in this browser"}</div>
            </div>
            <button onClick={() => setEditing(DEFAULT_CFG)} className="rounded-lg border border-border px-3 py-1.5 text-xs hover:bg-card">
              New chatbot
            </button>
          </div>

          <div className="space-y-3">
            <Field label="Chatbot name">
              <input value={editing.name} onChange={(e) => setEditing({ ...editing, name: e.target.value })} className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm" />
            </Field>
            <Field label="Widget title (shown in the chat header)">
              <input value={editing.widget_title} onChange={(e) => setEditing({ ...editing, widget_title: e.target.value })} className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm" />
            </Field>
            <Field label="Initial greeting">
              <input value={editing.welcome_message} onChange={(e) => setEditing({ ...editing, welcome_message: e.target.value })} className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm" />
            </Field>
            <Field label="System prompt (personality & knowledge)">
              <textarea rows={5} value={editing.system_prompt} onChange={(e) => setEditing({ ...editing, system_prompt: e.target.value })} className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm" />
            </Field>

            <div className="grid gap-3 sm:grid-cols-2">
              <Field label="Position on page">
                <select
                  value={editing.widget_position}
                  onChange={(e) => setEditing({ ...editing, widget_position: e.target.value as WidgetPosition })}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
                >
                  <option value="bottom-right">Bottom right</option>
                  <option value="bottom-left">Bottom left</option>
                  <option value="top-right">Top right</option>
                  <option value="top-left">Top left</option>
                </select>
              </Field>
              <Field label="Widget size">
                <select
                  value={editing.widget_size}
                  onChange={(e) => setEditing({ ...editing, widget_size: e.target.value as WidgetSize })}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
                >
                  <option value="small">Small (300×400)</option>
                  <option value="medium">Medium (340×480)</option>
                  <option value="large">Large (400×600)</option>
                  <option value="full">Extra large (480×700)</option>
                </select>
              </Field>
            </div>

            <div className="grid gap-3 sm:grid-cols-[1fr,110px]">
              <Field label="Logo URL (optional)">
                <input
                  value={editing.logo_url ?? ""}
                  onChange={(e) => setEditing({ ...editing, logo_url: e.target.value.trim() || null })}
                  placeholder="https://yoursite.com/logo.png"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Launcher icon">
                <input
                  value={editing.launcher_label}
                  maxLength={8}
                  onChange={(e) => setEditing({ ...editing, launcher_label: e.target.value || "💬" })}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-center text-sm"
                />
              </Field>
            </div>

            <Field label="Brand color">
              <div className="flex items-center gap-3">
                <input type="color" value={editing.brand_color} onChange={(e) => setEditing({ ...editing, brand_color: e.target.value })} className="h-10 w-14 cursor-pointer rounded-lg border border-border bg-background" />
                <input value={editing.brand_color} onChange={(e) => setEditing({ ...editing, brand_color: e.target.value })} className="w-32 rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm" />
                <label className="ml-auto flex items-center gap-2 text-xs">
                  <input type="checkbox" checked={editing.is_active} onChange={(e) => setEditing({ ...editing, is_active: e.target.checked })} /> Active
                </label>
              </div>
            </Field>

            {err && <div className="rounded-lg bg-destructive/10 p-2 text-xs text-destructive">{err}</div>}

            <button
              onClick={() => (ownerEmail ? void persist() : setPublishOpen(true))}
              disabled={saving}
              className="w-full rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground disabled:opacity-50"
            >
              {saving ? "Saving…" : ownerEmail ? (isSaved ? "Update chatbot" : "Save chatbot") : "Publish embed"}
            </button>
            {!ownerEmail && (
              <p className="text-xs text-muted-foreground">
                Everything above works without an account. When you publish, we ask for your name and email so we can host the embed script and send you the code.
              </p>
            )}
          </div>
        </div>

        {publishOpen && !ownerEmail && (
          <PublishPanel
            onCancel={() => setPublishOpen(false)}
            onDone={async (contact) => {
              const ok = await persist(contact);
              if (ok) setPublishOpen(false);
            }}
          />
        )}

        {isSaved && (
          <div className="glow-card rounded-2xl p-6">
            <div className="mb-2 text-xs uppercase tracking-widest text-primary">Embed on your website</div>
            <p className="mb-3 text-sm text-muted-foreground">
              Paste this snippet before <code>&lt;/body&gt;</code> on any page:
            </p>
            <pre className="overflow-x-auto rounded-lg bg-background/60 p-3 text-xs">{embedSnippet}</pre>
            <button
              onClick={() => {
                navigator.clipboard.writeText(embedSnippet);
                setCopied(true);
                setTimeout(() => setCopied(false), 1500);
              }}
              className="mt-3 inline-flex items-center gap-2 rounded-lg border border-border px-3 py-1.5 text-xs hover:bg-card"
            >
              {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
              {copied ? "Copied" : "Copy snippet"}
            </button>
            <p className="mt-3 text-xs text-muted-foreground">
              The widget picks up position, size, title, logo and greeting automatically. The public chat endpoint is rate limited and spam filtered.
            </p>
          </div>
        )}

        {isSaved && <AnalyticsPanel chatbotId={(editing as Chatbot).id} />}
      </div>

      <div className="space-y-4">
        <div className="glow-card rounded-2xl p-6">
          <div className="mb-3 text-sm font-semibold">Live preview</div>
          <ChatWindow
            key={isSaved ? (editing as Chatbot).id : "draft"}
            brandColor={editing.brand_color}
            welcome={editing.welcome_message}
            title={editing.widget_title}
            logoUrl={editing.logo_url}
            system={isSaved ? undefined : editing.system_prompt}
            configId={isSaved ? (editing as Chatbot).id : undefined}
          />
          <div className="mt-3 text-xs text-muted-foreground">
            Appears {editing.widget_position.replace("-", " ")} · {editing.widget_size} size · launcher “{editing.logo_url ? "logo" : editing.launcher_label}”
          </div>
        </div>

        {ownerEmail && (
          <div className="glow-card rounded-2xl p-6">
            <div className="mb-3 text-sm font-semibold">Your chatbots</div>
            {!items && <div className="text-sm text-muted-foreground">Loading…</div>}
            {items && items.length === 0 && <div className="text-sm text-muted-foreground">You haven't saved any chatbots yet.</div>}
            {items && items.length > 0 && (
              <ul className="space-y-2">
                {items.map((c) => (
                  <li key={c.id} className="flex items-center justify-between rounded-lg border border-border bg-background/60 p-3">
                    <button onClick={() => setEditing(c)} className="text-left">
                      <div className="text-sm font-medium">{c.name}</div>
                      <div className="text-xs text-muted-foreground">{c.is_active ? "Active" : "Paused"} · {c.brand_color}</div>
                    </button>
                    <button onClick={() => remove(c.id)} className="text-muted-foreground hover:text-destructive">
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </li>
                ))}
              </ul>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------------- Publish (name/email capture) ---------------- */

function PublishPanel({
  onCancel,
  onDone,
}: { onCancel: () => void; onDone: (contact: { contact_name: string; contact_email: string }) => Promise<void> }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [signInMode, setSignInMode] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setErr(null);
    try {
      if (signInMode) {
        const { error } = await supabase.auth.signInWithPassword({ email, password });
        if (error) throw error;
      } else {
        const { data: current } = await supabase.auth.getUser();
        if (current.user?.is_anonymous) {
          const { error } = await supabase.auth.updateUser({ email, password, data: { full_name: name } });
          if (error) throw error;
        } else {
          const { error } = await supabase.auth.signUp({
            email,
            password,
            options: { data: { full_name: name }, emailRedirectTo: window.location.origin + "/tools/chatbot" },
          });
          if (error) throw error;
        }
      }
      await onDone({ contact_name: name || email, contact_email: email });
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Something went wrong");
    } finally {
      setBusy(false);
    }
  }

  return (
    <form onSubmit={submit} className="glow-card space-y-3 rounded-2xl p-6">
      <div className="text-xs uppercase tracking-widest text-primary">Publish your embed</div>
      <div className="text-sm text-muted-foreground">
        Your draft is ready. Tell us where to send the embed script and we'll host your chatbot.
      </div>
      {!signInMode && (
        <input
          required placeholder="Your name" value={name} onChange={(e) => setName(e.target.value)} maxLength={120}
          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-primary"
        />
      )}
      <input
        type="email" required autoComplete="email" placeholder="you@company.com" value={email} onChange={(e) => setEmail(e.target.value)}
        className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-primary"
      />
      <input
        type="password" required minLength={8} autoComplete={signInMode ? "current-password" : "new-password"}
        placeholder="Password (min 8 chars)" value={password} onChange={(e) => setPassword(e.target.value)}
        className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-primary"
      />
      {err && <div className="rounded-lg bg-destructive/10 p-2 text-xs text-destructive">{err}</div>}
      <div className="flex gap-2">
        <button type="submit" disabled={busy} className="flex-1 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground disabled:opacity-50">
          {busy ? "Publishing…" : "Publish & get embed code"}
        </button>
        <button type="button" onClick={onCancel} className="rounded-lg border border-border px-4 py-2.5 text-sm hover:bg-card">
          Cancel
        </button>
      </div>
      <button type="button" onClick={() => setSignInMode(!signInMode)} className="w-full text-xs text-muted-foreground hover:text-foreground">
        {signInMode ? "New here? Create an account" : "Already have an account? Sign in"}
      </button>
    </form>
  );
}

/* ---------------- Analytics ---------------- */

type Analytics = {
  conversations: number;
  messages: number;
  user_messages: number;
  last_activity: string | null;
  daily: Array<{ day: string; messages: number }>;
};

function AnalyticsPanel({ chatbotId }: { chatbotId: string }) {
  const [data, setData] = useState<Analytics | null>(null);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    let alive = true;
    void (async () => {
      setData(null);
      setErr(null);
      try {
        const { getChatbotAnalytics } = await import("@/lib/chatbot.functions");
        const res = (await getChatbotAnalytics({ data: { id: chatbotId } })) as Analytics;
        if (alive) setData(res);
      } catch (e) {
        if (alive) setErr(e instanceof Error ? e.message : "Failed to load analytics");
      }
    })();
    return () => { alive = false; };
  }, [chatbotId]);

  const max = Math.max(1, ...(data?.daily ?? []).map((d) => d.messages));

  return (
    <div className="glow-card rounded-2xl p-6">
      <div className="mb-3 flex items-center gap-2 text-sm font-semibold">
        <BarChart3 className="h-4 w-4 text-primary" /> Performance
      </div>
      {err && <div className="rounded-lg bg-destructive/10 p-2 text-xs text-destructive">{err}</div>}
      {!data && !err && <div className="text-sm text-muted-foreground">Loading analytics…</div>}
      {data && (
        <>
          <div className="grid grid-cols-3 gap-3">
            <Stat label="Conversations" value={data.conversations} />
            <Stat label="Messages" value={data.messages} />
            <Stat label="Visitor messages" value={data.user_messages} />
          </div>
          <div className="mt-3 text-xs text-muted-foreground">
            Last activity: {data.last_activity ? new Date(data.last_activity).toLocaleString() : "no chats yet"}
          </div>
          <div className="mt-4">
            <div className="mb-2 text-xs uppercase tracking-widest text-muted-foreground">Messages per day (30 days)</div>
            {data.daily.length === 0 ? (
              <div className="text-sm text-muted-foreground">No activity recorded yet.</div>
            ) : (
              <div className="flex h-28 items-end gap-1">
                {data.daily.map((d) => (
                  <div key={d.day} className="flex-1" title={`${d.day}: ${d.messages}`}>
                    <div className="rounded-t bg-primary" style={{ height: `${(d.messages / max) * 100}%`, minHeight: 2 }} />
                  </div>
                ))}
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}

function Stat({ label, value }: { label: string; value: number }) {
  return (
    <div className="rounded-xl border border-border bg-background/60 p-3">
      <div className="font-display text-2xl font-bold">{value}</div>
      <div className="text-xs text-muted-foreground">{label}</div>
    </div>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <div className="mb-1 text-xs font-medium text-muted-foreground">{label}</div>
      {children}
    </label>
  );
}
