// Dashboard — scoped to the currently selected workspace.
function DashboardPage() {
  const auth = useAuth();
  const navigate = ReactRouterDOM.useNavigate();
  const ws = auth.currentWorkspace;
  const user = auth.session?.user;

  const [bookings, setBookings] = useState([]);
  const [activity, setActivity] = useState([]);
  const [eventSignupCount, setEventSignupCount] = useState(0);
  const [forms, setForms] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showNewBooking, setShowNewBooking] = useState(false);

  // Fetch everything when the workspace changes.
  useEffect(() => {
    if (!ws?.id) return;
    let cancelled = false;
    setLoading(true);
    (async () => {
      const [bookingsRes, activityRes, formsRes, eventsRes] = await Promise.all([
        SB.from('bookings')
          .select('id, starts_at, duration_min, status, customer_id, form_id, staff_resource_id, notes, customers(name, email)')
          .eq('workspace_id', ws.id)
          .order('starts_at'),
        SB.from('activity')
          .select('id, kind, text, created_at')
          .eq('workspace_id', ws.id)
          .order('created_at', { ascending: false })
          .limit(8),
        SB.from('forms').select('id, name, public_title').eq('workspace_id', ws.id),
        SB.from('events').select('id').eq('workspace_id', ws.id)
      ]);
      if (cancelled) return;
      setBookings(bookingsRes.data || []);
      setActivity(activityRes.data || []);
      setForms(formsRes.data || []);

      // Event signups: count across this workspace's events.
      const eventIds = (eventsRes.data || []).map(e => e.id);
      if (eventIds.length > 0) {
        const sgn = await SB.from('event_signups')
          .select('*', { count: 'exact', head: true })
          .in('event_id', eventIds);
        if (!cancelled) setEventSignupCount(sgn.count || 0);
      } else if (!cancelled) {
        setEventSignupCount(0);
      }
      setLoading(false);
    })();
    return () => { cancelled = true; };
  }, [ws?.id]);

  // Derived buckets.
  const now = new Date();
  const startOfToday = new Date(now); startOfToday.setHours(0,0,0,0);
  const endOfToday   = new Date(startOfToday); endOfToday.setDate(endOfToday.getDate() + 1);
  const weekAhead    = new Date(startOfToday); weekAhead.setDate(weekAhead.getDate() + 7);
  const formNameById = Object.fromEntries(forms.map(f => [f.id, f.public_title || f.name]));

  const enriched = bookings.map(b => ({
    ...b,
    _start: new Date(b.starts_at),
    _customer: b.customers,
    _formName: b.form_id ? (formNameById[b.form_id] || "Booking") : "Booking"
  }));

  const todays    = enriched.filter(b => b._start >= startOfToday && b._start < endOfToday);
  const upcoming  = enriched.filter(b => b._start > now && b._start < weekAhead);
  const pending   = enriched.filter(b => b.status === "requested");

  const fullDisplayName = displayNameFor(auth) || "there";
  const firstName = fullDisplayName.split(/\s+/)[0];
  const hour = now.getHours();
  const greeting = hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening";

  return (
    <div className="px-5 lg:px-7 py-7 max-w-[1400px] mx-auto">
      <PageHeader
        eyebrow={fmt(now, "EEEE, MMMM d")}
        title={`${greeting}, ${firstName}.`}
        subtitle={ws ? `Here's what's happening at ${ws.name} today.` : "Pick a workspace to see its data."}
        actions={
          <>
            <Button variant="secondary" icon="calendar-plus" onClick={() => setShowNewBooking(true)}>New booking</Button>
            <Button icon="plus" onClick={() => navigate("/app/events")}>New event</Button>
          </>
        }
      />

      <NewBookingModal
        open={showNewBooking}
        onClose={() => setShowNewBooking(false)}
        onCreated={() => {
          setShowNewBooking(false);
          // Re-fetch this workspace's data so the new booking appears in the lists.
          if (ws?.id) {
            (async () => {
              const r = await SB.from('bookings')
                .select('id, starts_at, duration_min, status, customer_id, form_id, staff_resource_id, notes, customers(name, email)')
                .eq('workspace_id', ws.id)
                .order('starts_at');
              setBookings(r.data || []);
            })();
          }
        }}
      />

      {/* Stat row */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <StatCard
          label="Today's appointments"
          value={todays.length}
          hint={`${todays.filter(t => t.status === "confirmed").length} confirmed · ${todays.filter(t => t.status === "requested").length} pending`}
          icon="calendar-check"
        />
        <StatCard label="Upcoming this week" value={upcoming.length} hint={upcoming.length === 0 ? "None yet" : `Across ${new Set(upcoming.map(b => b.form_id)).size} form${new Set(upcoming.map(b => b.form_id)).size === 1 ? "" : "s"}`} icon="calendar" />
        <StatCard label="Event signups" value={eventSignupCount} hint={`${eventSignupCount === 0 ? "No" : ""} signups so far`} icon="ticket" />
        <StatCard label="Pending requests" value={pending.length} hint="Awaiting your review" icon="clock" />
      </div>

      <div className="mt-6 grid lg:grid-cols-3 gap-5">
        {/* Today's schedule */}
        <div className="lg:col-span-2">
          <SectionCard title="Today's schedule" subtitle={fmt(now, "EEEE, MMMM d")} action={
            <Button variant="ghost" size="sm" iconRight="arrow-right" onClick={() => navigate("/app/calendar")}>Open calendar</Button>
          }>
            {loading ? (
              <div className="py-12 text-center text-[12.5px] text-ink/45">Loading…</div>
            ) : todays.length === 0 ? (
              <EmptyState icon="calendar" title="Nothing on today" body="No appointments scheduled. Take the morning." />
            ) : (
              <Timeline bookings={todays} />
            )}
          </SectionCard>

          {/* Pending requests */}
          <SectionCard className="mt-5" title="Pending requests" subtitle={`${pending.length} awaiting decision`} action={
            <Button variant="ghost" size="sm" iconRight="arrow-right" onClick={() => navigate("/app/bookings")}>All bookings</Button>
          }>
            {pending.length === 0 ? (
              <EmptyState icon="check" title="All caught up" body="No pending booking requests." />
            ) : (
              <div className="flex flex-col">
                {pending.map((b, i) => (
                  <div key={b.id} className={`flex items-center gap-3 py-3 ${i ? "border-t border-ink/[0.06]" : ""}`}>
                    <Avatar name={b._customer?.name || "?"} size={32} />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 text-[13.5px]">
                        <span className="font-medium truncate">{b._customer?.name || "Unknown"}</span>
                        <Badge tone="warn" dot>Pending</Badge>
                      </div>
                      <div className="text-[12px] text-ink/55 truncate">
                        {b._formName} · {fmt(b._start, "EEE MMM d")} at {fmt(b._start, "h:mma").toLowerCase()}
                      </div>
                    </div>
                    <div className="hidden md:flex items-center gap-1.5">
                      <Button variant="ghost" size="sm" icon="x">Decline</Button>
                      <Button size="sm" icon="check">Approve</Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </SectionCard>
        </div>

        {/* Sidebar column */}
        <div className="flex flex-col gap-5">
          {/* Quick actions */}
          <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">Quick actions</div>
            <div className="grid grid-cols-2 gap-2">
              {[
                { label: "Add booking",  icon: "calendar-plus", to: "/app/bookings" },
                { label: "Create event", icon: "plus",          to: "/app/events" },
                { label: "Add customer", icon: "user-plus",     to: "/app/customers" },
                { label: "Edit form",    icon: "file-pen",      to: "/app/forms" },
                { label: "Block time",   icon: "ban",           to: "/app/calendar" },
                { label: "Edit emails",  icon: "send",          to: "/app/automations" }
              ].map((q) => (
                <button
                  key={q.label}
                  onClick={() => navigate(q.to)}
                  className="flex flex-col items-start gap-2 px-3 py-2.5 rounded-md border border-ink/[0.06] hover:bg-white hover:border-ink/[0.10] text-left transition"
                >
                  <Icon name={q.icon} size={14} className="text-ink/65" />
                  <span className="text-[12px]">{q.label}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Activity */}
          <div className="rounded-lg border border-ink/[0.06] bg-white p-5">
            <div className="flex items-center justify-between mb-3">
              <div className="text-[11px] uppercase tracking-[0.1em] text-ink/50">Recent activity</div>
            </div>
            {activity.length === 0 ? (
              <div className="text-[12.5px] text-ink/45 py-3">No activity yet — bookings and signups appear here.</div>
            ) : (
              <div className="flex flex-col">
                {activity.map((a, i) => (
                  <div key={a.id} className={`flex items-start gap-3 py-2.5 ${i ? "border-t border-ink/[0.05]" : ""}`}>
                    <div className={`h-6 w-6 rounded-full grid place-items-center mt-0.5 ${activityTone(a.kind).bg}`}>
                      <Icon name={activityTone(a.kind).icon} size={11} className={activityTone(a.kind).text} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="text-[12.5px] text-ink/85 leading-snug">{a.text}</div>
                      <div className="text-[11px] text-ink/45 mt-0.5">{relTime(new Date(a.created_at))}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Upcoming */}
      <SectionCard className="mt-5" title="Upcoming bookings" subtitle="Next 7 days" action={
        <Button variant="ghost" size="sm" iconRight="arrow-right" onClick={() => navigate("/app/bookings")}>All bookings</Button>
      }>
        {upcoming.length === 0 ? (
          <EmptyState icon="calendar" title="No upcoming bookings" body="When customers book through your public page, they'll appear here." />
        ) : (
          <div className="overflow-x-auto -mx-5">
            <table className="w-full text-[13px]">
              <thead className="text-[11px] uppercase tracking-[0.08em] text-ink/45">
                <tr className="border-b border-ink/[0.06]">
                  <th className="text-left font-medium px-5 py-2.5">Customer</th>
                  <th className="text-left font-medium px-2 py-2.5">Form</th>
                  <th className="text-left font-medium px-2 py-2.5">When</th>
                  <th className="text-left font-medium px-2 py-2.5">Status</th>
                  <th className="text-right font-medium px-5 py-2.5"></th>
                </tr>
              </thead>
              <tbody>
                {upcoming.slice(0, 6).map((b) => (
                  <tr key={b.id} className="border-b border-ink/[0.04] hover:bg-white">
                    <td className="px-5 py-3">
                      <div className="flex items-center gap-2.5">
                        <Avatar name={b._customer?.name || "?"} size={26} />
                        <div>
                          <div className="font-medium">{b._customer?.name || "Unknown"}</div>
                          <div className="text-[11.5px] text-ink/50">{b._customer?.email || ""}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-2 py-3">{b._formName}</td>
                    <td className="px-2 py-3">{fmt(b._start, "EEE MMM d")} · <span className="text-ink/65">{fmt(b._start, "h:mma").toLowerCase()}</span></td>
                    <td className="px-2 py-3"><StatusBadge status={b.status} /></td>
                    <td className="px-5 py-3 text-right">
                      <button className="text-ink/55 hover:text-ink p-1"><Icon name="chevron-right" size={14} /></button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>
    </div>
  );
}

function SectionCard({ title, subtitle, action, children, className = "" }) {
  return (
    <section className={`rounded-lg border border-ink/[0.06] bg-white ${className}`}>
      <header className="flex items-center justify-between px-5 py-3.5 border-b border-ink/[0.06]">
        <div>
          <h3 className="text-[14px] font-medium">{title}</h3>
          {subtitle && <div className="text-[11.5px] text-ink/50 mt-0.5">{subtitle}</div>}
        </div>
        {action}
      </header>
      <div className="p-5">{children}</div>
    </section>
  );
}

function Timeline({ bookings }) {
  const startH = 8, endH = 20;
  const totalH = endH - startH;
  const now = new Date();
  const nowOffset = ((now.getHours() + now.getMinutes()/60) - startH) / totalH * 100;
  return (
    <div className="relative">
      <div className="flex gap-3">
        <div className="flex flex-col text-[10.5px] text-ink/40 pt-1" style={{ width: 36 }}>
          {Array.from({length: totalH+1}, (_, i) => (
            <div key={i} className="h-12 -mt-1.5 first:mt-0">
              <span>{((startH + i) % 12 || 12)}{startH + i < 12 ? "a" : "p"}</span>
            </div>
          ))}
        </div>
        <div className="relative flex-1 border-l border-ink/[0.06]">
          {Array.from({length: totalH}, (_, i) => (
            <div key={i} className="h-12 border-b border-ink/[0.04]" />
          ))}
          {nowOffset > 0 && nowOffset < 100 && (
            <div className="absolute left-0 right-0 pointer-events-none" style={{ top: `${nowOffset}%` }}>
              <div className="h-px bg-accent/70" />
              <div className="absolute -left-1 -top-1 h-2 w-2 rounded-full bg-accent" />
            </div>
          )}
          {bookings.map((b) => {
            const start = b._start;
            const startMin = start.getHours() + start.getMinutes()/60;
            const top = (startMin - startH) / totalH * 100;
            const height = (b.duration_min / 60) / totalH * 100;
            return (
              <div key={b.id} className="absolute left-2 right-2 rounded-md border bg-white border-ink/[0.08] p-2.5 backdrop-blur-sm overflow-hidden"
                style={{ top: `${top}%`, height: `${height}%`, borderLeft: `3px solid ${b.status === "requested" ? "#B07A2A" : "#3D7BB0"}` }}
              >
                <div className="flex items-center justify-between gap-2">
                  <div className="text-[12.5px] font-medium truncate">{b._customer?.name || "—"}</div>
                  <span className="text-[11px] text-ink/55">{fmt(start, "h:mma").toLowerCase()}</span>
                </div>
                <div className="text-[11.5px] text-ink/60 truncate">{b._formName}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function sameDay(a, b) {
  return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}
function relTime(d) {
  const now = new Date();
  const diff = (now - d) / 1000;
  if (diff < 60) return "just now";
  if (diff < 3600) return Math.floor(diff/60) + "m ago";
  if (diff < 86400) return Math.floor(diff/3600) + "h ago";
  return Math.floor(diff/86400) + "d ago";
}
function activityTone(kind) {
  const map = {
    booking:  { icon: "calendar-check", bg: "bg-accent/15",  text: "text-[#9CC3E6]" },
    request:  { icon: "clock",          bg: "bg-warn/15",    text: "text-[#E0B775]" },
    event:    { icon: "ticket",         bg: "bg-ok/15",      text: "text-[#86C9A6]" },
    customer: { icon: "user",           bg: "bg-ink/[0.04]", text: "text-ink/70" },
    cancel:   { icon: "x",              bg: "bg-danger/15",  text: "text-[#D69898]" },
    form:     { icon: "file-text",      bg: "bg-ink/[0.04]", text: "text-ink/70" }
  };
  return map[kind] || map.customer;
}

Object.assign(window, { DashboardPage, SectionCard, sameDay, relTime, activityTone });
