/* Dashboard — daily briefing for current user */

function PageDashboard({ onNavigate }) {
  /* Total record counts from the live DB (binary-search probe at boot),
     so the KPI shows "3,994 target accounts" rather than just what's
     currently loaded into memory. */
  const apiTotals = window.useApiTotals ? window.useApiTotals() : null;
  const myTasks   = window.TASKS.filter(t => t.assignedUserId === CURRENT_USER.id && t.status !== "done");
  const myOpps    = window.OPPORTUNITIES.filter(o => o.owner === CURRENT_USER.id);
  const today     = window.CALENDAR_EVENTS.filter(e => e.day === "2026-05-21" || e.day === "2026-05-22");
  const totalPipe = myOpps.reduce((s, o) => s + (o.value || 0), 0);
  const [briefLoading, setBriefLoading] = React.useState(false);
  const [briefGeneratedAt, setBriefGeneratedAt] = React.useState("7:02 AM");
  const [activeEvent, setActiveEvent] = React.useState(null);

  /* Editable AI brief items — user can rewrite title/body inline. */
  const [briefItems, setBriefItems] = React.useState([
    {
      id: "b1",
      kicker: "Priority for today", tone: "warm", icon: "flag",
      title: "Mango is ready to receive proposal v2",
      body: "Judit Pons explicitly asked about pricing for a 14k-employee org. Send the deck before noon.",
      action: "Open conversation",
      target: { page: "conversations", state: { conversationId: "conv-judit" } },
    },
    {
      id: "b2",
      kicker: "Best new connect", tone: "violet", icon: "user-plus",
      title: "Carla Medina — Head of TA, Neuraxpharm",
      body: "No relationship yet, but role fits ICP. AI-drafted invite is ready to review.",
      action: "Review invite",
      target: { page: "contacts" },
    },
    {
      id: "b3",
      kicker: "At risk", tone: "red", icon: "alert",
      title: "Majestic Hotel Group · 1 contact mapped",
      body: "Only Pilar mapped — recommend identifying CFO + ops director before discovery.",
      action: "Open account",
      target: { page: "account-detail", state: { companyId: "277567" } },
    },
  ]);

  const updateBriefItem = (id, patch) => {
    setBriefItems(prev => prev.map(it => it.id === id ? { ...it, ...patch } : it));
  };

  const regenerate = () => {
    setBriefLoading(true);
    setTimeout(() => {
      setBriefLoading(false);
      const t = new Date();
      setBriefGeneratedAt(t.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }));
    }, 1200);
  };

  return (
    <>
      <PageHeader
        kicker={fmtDate(new Date(), { weekday: "long", day: "2-digit", month: "long" })}
        title={<>Good morning, <span style={{ color: "var(--ink)" }}>{CURRENT_USER.name.split(" ")[0]}.</span></>}
        actions={<>
          <Button kind="secondary" size="md" icon="refresh">Refresh</Button>
          <Button kind="primary" size="md" icon="sparkles" onClick={regenerate}>AI brief</Button>
        </>}
      />

      <div className="page-pad page-pad-y" style={{ display: "flex", flexDirection: "column", gap: 24 }}>
        {/* KPI strip — single row, always */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, minmax(0, 1fr))",
          gap: 12,
        }}>
          <KpiTile icon="building" label="Target accounts" value={(apiTotals?.companies ?? window.COMPANIES.length).toLocaleString()} delta="+2" tone="violet" />
          <KpiTile icon="user-check" label="Connected contacts" value={window.CONTACTS.filter(c => c.linkedinStatus === "accepted").length.toLocaleString()} delta="+5" tone="green" />
          <KpiTile icon="kanban" label="Pipeline value" value={fmtCurrency(totalPipe, "EUR")} delta="+12%" tone="warm" />
          <KpiTile icon="messages" label="Active conversations" value={window.CONVERSATIONS.length} delta="3 unread" tone="blue" />
        </div>

        {/* AI Daily Brief — auto-advancing carousel, ~½ the previous height */}
        <Card padding={0} style={{
          border: "1px solid color-mix(in oklch, var(--accent) 22%, var(--line))",
          background: "linear-gradient(180deg, color-mix(in oklch, var(--accent) 5%, var(--surface)), var(--surface))",
          overflow: "hidden",
        }}>
          <DailyBriefCarousel
            loading={briefLoading}
            generatedAt={briefGeneratedAt}
            onRegenerate={regenerate}
            items={briefItems.map(it => ({
              ...it,
              onAction: () => onNavigate(it.target.page, it.target.state),
              onEdit: (patch) => updateBriefItem(it.id, patch),
            }))}
          />
        </Card>

        <div className="dash-2col">
          {/* My day */}
          <Card padding={0}>
            <SectionHeader title={<span>My day · <span style={{ fontWeight: 400, color: "var(--ink-3)" }}>{today.length} events, {myTasks.length} tasks</span></span>}
              right={<Button kind="ghost" size="sm" iconRight="arrow-right" onClick={() => onNavigate("calendar")}>Open calendar</Button>} />
            <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 14 }}>
              {today.slice(0, 4).map(ev => (
                <button
                  key={ev.id}
                  onClick={() => setActiveEvent(ev)}
                  style={{
                    display: "grid", gridTemplateColumns: "60px 1fr auto",
                    gap: 14, alignItems: "center",
                    padding: 6, margin: -6, borderRadius: 8,
                    width: "calc(100% + 12px)", textAlign: "left",
                    transition: "background 120ms",
                    cursor: "pointer",
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"}
                  onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
                >
                  <div style={{ textAlign: "right" }}>
                    <div className="mono" style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)" }}>{ev.start}</div>
                    <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{ev.end}</div>
                  </div>
                  <div style={{
                    padding: 10, borderRadius: 8,
                    background: ev.type === "account_review" ? "var(--accent-soft)" : "var(--surface-2)",
                    border: "1px solid var(--line)",
                    borderLeft: `2px solid ${ev.type === "account_review" ? "var(--accent)" : "var(--blue)"}`,
                  }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{ev.title}</div>
                    <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 1 }}>
                      <Icon name="map-pin" size={10} style={{ marginRight: 2, verticalAlign: "middle" }} />
                      {ev.location}
                    </div>
                  </div>
                  <div style={{ display: "flex" }}>
                    {ev.attendees.slice(0, 3).map((a, i) => {
                      const u = getUser(a);
                      const ct = window.CONTACTS.find(c => c.id === a);
                      return <div key={a} style={{ marginLeft: i > 0 ? -8 : 0 }}>
                        <Avatar name={u?.name || `${ct?.firstName} ${ct?.lastName}`} src={ct?.profilePictureUrl} size={22} />
                      </div>;
                    })}
                  </div>
                </button>
              ))}
            </div>
          </Card>

          {/* Tasks */}
          <Card padding={0}>
            <SectionHeader title={`Open tasks · ${myTasks.length}`}
              right={<Button kind="ghost" size="sm" iconRight="arrow-right" onClick={() => onNavigate("tasks")}>All tasks</Button>} />
            <div style={{ padding: "4px 0" }}>
              {myTasks.slice(0, 5).map(t => <TaskRow key={t.id} t={t} />)}
            </div>
          </Card>
        </div>

        <div className="dash-2col-eq">
          {/* Pipeline */}
          <Card padding={0}>
            <SectionHeader title="Pipeline by stage"
              right={<Button kind="ghost" size="sm" iconRight="arrow-right" onClick={() => onNavigate("opportunities")}>Open pipeline</Button>} />
            <div style={{ padding: 16 }}>
              <PipelineByStage />
            </div>
          </Card>

          {/* LinkedIn sync */}
          <Card padding={0}>
            <SectionHeader title="LinkedIn graph health"
              right={<Button kind="ghost" size="sm" icon="refresh">Sync now</Button>} />
            <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
              <SyncStatRow label="Total LinkedIn connections" value={2335} />
              <SyncStatRow label="Synced contacts" value={137} sub="6 pages · last 2h ago" />
              <SyncStatRow label="Pending invitations sent" value={252} sub="Within rate limits" />
              <SyncStatRow label="Acceptance rate (30d)" value="38%" sub="Above benchmark 24%" tone="green" />
              <div style={{ padding: 10, background: "var(--accent-soft)", borderRadius: 8, display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
                <Icon name="sparkles" size={12} style={{ color: "var(--accent)" }} />
                <span><b>Tip:</b> personalized invites have a 71% accept rate. <a href="#" style={{ color: "var(--accent-ink)", fontWeight: 600 }}>Enable AI personalization →</a></span>
              </div>
            </div>
          </Card>
        </div>
      </div>

      {/* Event detail modal — reused from calendar */}
      <window.EventDetailModal
        ev={activeEvent}
        onClose={() => setActiveEvent(null)}
        onOpenAccount={(id) => { setActiveEvent(null); onNavigate("account-detail", { companyId: id }); }}
      />
    </>
  );
}

function KpiTile({ icon, label, value, delta, tone }) {
  const colors = { violet: "var(--accent)", green: "var(--green)", warm: "var(--warm)", blue: "var(--blue)" };
  return (
    <Card padding={14} style={{ display: "flex", flexDirection: "column", gap: 6, minWidth: 0 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
        <div style={{
          width: 24, height: 24, borderRadius: 6,
          background: "var(--inset)", color: colors[tone],
          display: "flex", alignItems: "center", justifyContent: "center",
          flexShrink: 0,
        }}>
          <Icon name={icon} size={13} />
        </div>
        <span style={{
          fontSize: 11.5, color: "var(--ink-3)", fontWeight: 500,
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
          minWidth: 0,
        }}>{label}</span>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 6, minWidth: 0 }}>
        <span className="num" style={{
          fontSize: "clamp(16px, 1.7vw, 22px)",
          fontWeight: 600, letterSpacing: "-0.02em",
          color: "var(--ink)",
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
          minWidth: 0,
        }}>{value}</span>
        <span style={{
          fontSize: 11, color: "var(--green-ink)", fontWeight: 600,
          whiteSpace: "nowrap", flexShrink: 0,
        }}>{delta}</span>
      </div>
    </Card>
  );
}

function BriefBlock({ kicker, tone, icon, title, body, action, onAction }) {
  const toneInk = ({ violet: "var(--accent-ink)", warm: "var(--warm-ink)", red: "var(--red-ink)" })[tone];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 5, color: toneInk, fontSize: 11, fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase" }}>
        <Icon name={icon} size={11} />
        {kicker}
      </div>
      <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)", lineHeight: 1.4, letterSpacing: "-0.005em" }}>{title}</div>
      <div style={{ fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.5 }}>{body}</div>
      <button onClick={onAction} style={{ marginTop: 4, alignSelf: "flex-start", fontSize: 12, fontWeight: 600, color: "var(--ink)", display: "inline-flex", alignItems: "center", gap: 4 }}>
        {action} <Icon name="arrow-right" size={11} />
      </button>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────
   Daily Brief Carousel — auto-advances, pauses on hover, compact height.
   One slide visible at a time, ~half the height of the old 3-up grid.
   ───────────────────────────────────────────────────────────────────── */
function DailyBriefCarousel({ items, loading, generatedAt, onRegenerate }) {
  const [idx, setIdx]       = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const [editing, setEditing] = React.useState(null); /* `${idx}:title` | `${idx}:body` */
  const trackRef = React.useRef(null);

  /* auto-advance every 5s */
  React.useEffect(() => {
    if (paused || editing || loading || items.length <= 1) return;
    const t = setInterval(() => setIdx(i => (i + 1) % items.length), 5000);
    return () => clearInterval(t);
  }, [paused, editing, loading, items.length]);

  const TONES = {
    warm:   { fg: "var(--warm-ink)",   bg: "var(--warm-soft)",   bd: "var(--warm)" },
    violet: { fg: "var(--accent-ink)", bg: "var(--accent-soft)", bd: "var(--accent)" },
    red:    { fg: "var(--red-ink)",    bg: "var(--red-soft)",    bd: "var(--red)" },
  };

  if (loading) {
    return (
      <div style={{ padding: "12px 16px 14px", display: "flex", alignItems: "center", gap: 14 }}>
        <Icon name="sparkles" size={14} style={{ color: "var(--accent)" }} />
        <div className="shimmer" style={{ height: 12, width: 100, flexShrink: 0 }} />
        <div className="shimmer" style={{ height: 14, width: "55%", flex: 1 }} />
        <div className="shimmer" style={{ height: 22, width: 90, flexShrink: 0, borderRadius: 999 }} />
      </div>
    );
  }

  return (
    <div
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      style={{ position: "relative" }}
    >
      {/* Title row */}
      <div style={{
        padding: "10px 16px 0",
        display: "flex", alignItems: "center", gap: 8,
        fontSize: 11.5, fontWeight: 600, color: "var(--ink-2)",
      }}>
        <Icon name="sparkles" size={12} style={{ color: "var(--accent)" }} />
        <span>AI daily brief</span>
        <AIChip>generated {generatedAt}</AIChip>
        <span style={{ flex: 1 }} />
        <button
          onClick={onRegenerate}
          title="Regenerate"
          style={{
            width: 22, height: 22, borderRadius: 5,
            color: "var(--ink-3)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            transition: "background 120ms, color 120ms",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = "var(--inset)"; e.currentTarget.style.color = "var(--ink)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink-3)"; }}
        ><Icon name="refresh" size={11} /></button>
      </div>

      {/* Slide viewport */}
      <div style={{ overflow: "hidden", padding: "8px 16px 14px" }}>
        <div
          ref={trackRef}
          style={{
            display: "flex",
            transform: `translateX(-${idx * 100}%)`,
            transition: "transform 480ms cubic-bezier(0.2, 0.7, 0.2, 1)",
          }}
        >
          {items.map((s, i) => {
            const t = TONES[s.tone] || TONES.violet;
            const editKey = (field) => `${i}:${field}`;
            const isEditing = (field) => editing === editKey(field);
            const commit = (field) => (e) => {
              const next = e.currentTarget.innerText.replace(/\s+/g, " ").trim();
              if (next && next !== s[field]) s.onEdit && s.onEdit({ [field]: next });
              else e.currentTarget.innerText = s[field]; /* revert empties */
              setEditing(null);
            };
            const editableProps = (field) => ({
              contentEditable: true,
              suppressContentEditableWarning: true,
              spellCheck: true,
              onFocus: () => setEditing(editKey(field)),
              onBlur: commit(field),
              onKeyDown: (e) => {
                if (e.key === "Enter") { e.preventDefault(); e.currentTarget.blur(); }
                if (e.key === "Escape") { e.preventDefault(); e.currentTarget.innerText = s[field]; e.currentTarget.blur(); }
              },
              onClick: (e) => e.stopPropagation(),
            });
            return (
              <div key={s.id || i} style={{ flex: "0 0 100%", minWidth: 0 }}>
                <div style={{
                  display: "flex", alignItems: "center", gap: 12,
                  minHeight: 56,
                }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: 8,
                    background: t.bg, color: t.fg,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    flexShrink: 0,
                  }}>
                    <Icon name={s.icon} size={14} />
                  </div>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{
                      display: "flex", alignItems: "center", gap: 6,
                      fontSize: 10.5, fontWeight: 600, letterSpacing: "0.05em",
                      color: t.fg, textTransform: "uppercase",
                      marginBottom: 2,
                    }}>
                      {s.kicker}
                      <Icon
                        name="edit"
                        size={10}
                        title="Click title or body to edit"
                        style={{
                          color: "var(--ink-4)",
                          opacity: i === idx ? 0.6 : 0,
                          transition: "opacity 160ms",
                        }}
                      />
                    </div>
                    <div
                      {...editableProps("title")}
                      style={{
                        fontSize: 13.5, fontWeight: 600, color: "var(--ink)",
                        letterSpacing: "-0.005em",
                        overflow: "hidden", textOverflow: "ellipsis",
                        whiteSpace: isEditing("title") ? "normal" : "nowrap",
                        outline: "none",
                        borderRadius: 4,
                        padding: "1px 4px", margin: "-1px -4px",
                        background: isEditing("title") ? "var(--surface)" : "transparent",
                        boxShadow: isEditing("title") ? "inset 0 0 0 1.5px color-mix(in oklch, var(--accent) 50%, transparent)" : "none",
                        cursor: "text",
                        transition: "background 120ms, box-shadow 120ms",
                      }}
                      onMouseEnter={(e) => { if (!isEditing("title")) e.currentTarget.style.background = "var(--inset)"; }}
                      onMouseLeave={(e) => { if (!isEditing("title")) e.currentTarget.style.background = "transparent"; }}
                    >{s.title}</div>
                    <div
                      {...editableProps("body")}
                      style={{
                        fontSize: 11.5, color: "var(--ink-3)",
                        overflow: "hidden", textOverflow: "ellipsis",
                        whiteSpace: isEditing("body") ? "normal" : "nowrap",
                        marginTop: 1,
                        outline: "none",
                        borderRadius: 4,
                        padding: "1px 4px", margin: "1px -4px 0",
                        background: isEditing("body") ? "var(--surface)" : "transparent",
                        boxShadow: isEditing("body") ? "inset 0 0 0 1.5px color-mix(in oklch, var(--accent) 50%, transparent)" : "none",
                        cursor: "text",
                        transition: "background 120ms, box-shadow 120ms",
                      }}
                      onMouseEnter={(e) => { if (!isEditing("body")) e.currentTarget.style.background = "var(--inset)"; }}
                      onMouseLeave={(e) => { if (!isEditing("body")) e.currentTarget.style.background = "transparent"; }}
                    >{s.body}</div>
                  </div>
                  <button
                    onClick={s.onAction}
                    style={{
                      flexShrink: 0,
                      padding: "5px 10px", borderRadius: 999,
                      background: "var(--ink)", color: "#fff",
                      fontSize: 11.5, fontWeight: 600,
                      display: "inline-flex", alignItems: "center", gap: 4,
                      boxShadow: "inset 0 1px 0 rgba(255,255,255,0.08)",
                    }}
                  >
                    {s.action}
                    <Icon name="arrow-right" size={11} />
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Progress dots */}
      <div style={{
        position: "absolute", bottom: 5, left: 0, right: 0,
        display: "flex", justifyContent: "center", gap: 5,
        pointerEvents: "none",
      }}>
        {items.map((_, i) => (
          <button
            key={i}
            onClick={() => setIdx(i)}
            aria-label={`Slide ${i + 1}`}
            style={{
              width: i === idx ? 14 : 5, height: 4, borderRadius: 999,
              background: i === idx ? "var(--accent)" : "var(--line-strong)",
              transition: "width 280ms, background 280ms",
              pointerEvents: "auto",
            }}
          />
        ))}
      </div>
    </div>
  );
}

function TaskRow({ t }) {
  const company = getCompany(t.companyId);
  return (
    <div style={{
      display: "grid", gridTemplateColumns: "24px 1fr auto",
      padding: "10px 16px", borderBottom: "1px solid var(--line)",
      alignItems: "center", gap: 10,
    }}>
      <button style={{
        width: 16, height: 16, borderRadius: "50%",
        border: "1.5px solid var(--line-strong)", background: "var(--surface)",
      }} title="Mark done" />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, color: "var(--ink)", fontWeight: 500 }}>{t.title}</div>
        <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 1 }}>
          {company && <span>{company.name} · </span>}
          due {fmtRelative(t.dueAt)}
        </div>
      </div>
      <Badge tone={t.priority === "high" ? "warm" : t.priority === "medium" ? "blue" : "neutral"} size="sm">
        {t.priority}
      </Badge>
    </div>
  );
}

function PipelineByStage() {
  const stages = window.OPPORTUNITY_STAGES.slice(0, 6);
  const byStage = stages.map(s => {
    const opps = window.OPPORTUNITIES.filter(o => o.stage === s.id);
    return { ...s, count: opps.length, value: opps.reduce((acc, o) => acc + (o.value || 0), 0) };
  });
  const max = Math.max(...byStage.map(s => s.value), 1);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      {byStage.map(s => (
        <div key={s.id} style={{ display: "grid", gridTemplateColumns: "120px 1fr 100px", gap: 10, alignItems: "center" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: "50%", background: ({ violet: "var(--accent)", warm: "var(--warm)", green: "var(--green)", blue: "var(--blue)", neutral: "var(--ink-4)" })[s.tone] }} />
            <span style={{ fontSize: 12, color: "var(--ink-2)" }}>{s.label}</span>
            <span className="mono num" style={{ fontSize: 11, color: "var(--ink-4)" }}>{s.count}</span>
          </div>
          <div style={{ height: 8, background: "var(--inset)", borderRadius: 4 }}>
            <div style={{
              width: `${(s.value / max) * 100}%`, height: "100%", borderRadius: 4,
              background: ({ violet: "var(--accent)", warm: "var(--warm)", green: "var(--green)", blue: "var(--blue)", neutral: "var(--ink-4)" })[s.tone],
            }} />
          </div>
          <span className="mono num" style={{ fontSize: 12, textAlign: "right", fontWeight: 600 }}>{fmtCurrency(s.value, "EUR")}</span>
        </div>
      ))}
    </div>
  );
}

function SyncStatRow({ label, value, sub, tone = "neutral" }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14 }}>
      <div>
        <div style={{ fontSize: 12, color: "var(--ink-2)" }}>{label}</div>
        {sub && <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 1 }}>{sub}</div>}
      </div>
      <div className="mono num" style={{ fontSize: 16, fontWeight: 600, color: tone === "green" ? "var(--green-ink)" : "var(--ink)" }}>
        {typeof value === "number" ? value.toLocaleString() : value}
      </div>
    </div>
  );
}

window.PageDashboard = PageDashboard;
