// Dashboard view: hero + today + overdue + upcoming events

function StatCard({ icon, label, value, hint, accent = "var(--terracotta)", bg = "var(--terracotta-tint)" }) {
  return (
    <Card padding={18} style={{ minWidth: 0 }}>
      <div className="row gap-3" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
        <div className="col gap-1" style={{ minWidth: 0 }}>
          <div className="tiny">{label}</div>
          <div className="stat-value" style={{ fontFamily: "var(--font-display)", fontSize: 38, lineHeight: 1, color: "var(--ink)" }}>{value}</div>
          {hint && <div className="small muted" style={{ marginTop: 4 }}>{hint}</div>}
        </div>
        <div style={{ width: 40, height: 40, borderRadius: 12, background: bg, color: accent, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name={icon} size={18} />
        </div>
      </div>
    </Card>
  );
}

function DashboardHero({ items, openForm, user }) {
  const userInfo = (typeof USERS !== "undefined" && USERS[user]) || { name: user || "vous" };
  const today = TODAY;
  const greeting = (() => {
    const h = today.getHours();
    if (h < 12) return "Bonjour";
    if (h < 18) return "Bon après-midi";
    return "Bonsoir";
  })();
  const todayItems = itemsOnDate(items, today);
  const tasksToday = todayItems.filter(x => x.kind === "task");
  const remaining = tasksToday.filter(x => {
    const s = statusOn(x, today);
    return s === "todo" || s === "progress";
  }).length;
  const done = tasksToday.filter(x => statusOn(x, today) === "done").length;
  const total = tasksToday.length;

  return (
    <div className="hero-card" style={{
      position: "relative",
      borderRadius: 24,
      padding: "32px 32px 28px",
      background: "linear-gradient(135deg, #F8E5D5 0%, #F3D4BD 60%, #EFC7AC 100%)",
      border: "1px solid #EAD2BE",
      overflow: "hidden",
    }}>
      {/* Decorative arc */}
      <svg width="280" height="280" viewBox="0 0 280 280" style={{ position: "absolute", right: -40, top: -40, opacity: 0.5 }}>
        <circle cx="140" cy="140" r="120" stroke="#C2603F" strokeWidth="1" fill="none" opacity="0.4" />
        <circle cx="140" cy="140" r="80" stroke="#C2603F" strokeWidth="1" fill="none" opacity="0.3" />
        <circle cx="140" cy="140" r="40" stroke="#C2603F" strokeWidth="1" fill="none" opacity="0.2" />
      </svg>

      <div className="col gap-4" style={{ position: "relative" }}>
        <div className="col gap-1">
          <div className="tiny" style={{ color: "var(--terracotta-2)" }}>{fmtFull(today)}</div>
          <h1 className="hero-title" style={{ fontFamily: "var(--font-display)", fontSize: 52, fontWeight: 400, lineHeight: 1.05, margin: 0, color: "var(--ink)", letterSpacing: "-0.02em" }}>
            {greeting}, {userInfo.name}.
            <br />
            <span style={{ fontStyle: "italic", color: "var(--terracotta-2)" }}>
              {remaining > 0
                ? `${remaining} chose${remaining > 1 ? "s" : ""} à faire`
                : total > 0 ? "tout est sous contrôle." : "rien de prévu aujourd'hui."}
            </span>
          </h1>
        </div>

        <div className="row gap-4" style={{ alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 12 }}>
            <div style={{ position: "relative", width: 64, height: 64 }}>
              <svg width="64" height="64" viewBox="0 0 64 64" style={{ position: "absolute", inset: 0, transform: "rotate(-90deg)" }}>
                <circle cx="32" cy="32" r="26" stroke="#FFFFFF80" strokeWidth="6" fill="none" />
                <circle cx="32" cy="32" r="26" stroke="var(--terracotta-2)" strokeWidth="6" fill="none"
                  strokeDasharray={2 * Math.PI * 26}
                  strokeDashoffset={2 * Math.PI * 26 * (1 - (total ? done / total : 0))}
                  strokeLinecap="round"
                  style={{ transition: "stroke-dashoffset .6s ease" }} />
              </svg>
              <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-display)", fontSize: 22, color: "var(--ink)" }}>
                {done}<span style={{ fontSize: 12, color: "var(--ink-3)", marginLeft: 1 }}>/{total}</span>
              </div>
            </div>
            <div className="col" style={{ gap: 0 }}>
              <div style={{ fontWeight: 500 }}>Aujourd'hui</div>
              <div className="small muted">{total === 0 ? "Aucune tâche" : `${done} terminée${done > 1 ? "s" : ""} sur ${total}`}</div>
            </div>
          </div>

          <div style={{ width: 1, height: 32, background: "#FFFFFF80" }} />

          <Button variant="primary" icon="plus" onClick={() => openForm()}>Nouvelle tâche</Button>
        </div>
      </div>
    </div>
  );
}

function TaskRow({ item, date, onStatusChange, onEdit, dense }) {
  const isTask = item.kind === "task";
  const status = statusOn(item, date);
  const s = STATES[status];
  const k = KINDS[item.kind];

  const cycleStatus = () => {
    if (!isTask) return;
    const order = ["todo", "progress", "done"];
    const i = order.indexOf(status);
    const next = i === -1 || i === order.length - 1 ? "todo" : order[i + 1];
    onStatusChange(item.id, ymd(date), next);
  };

  return (
    <div
      className="row gap-3"
      style={{
        padding: dense ? "10px 12px" : "14px 14px",
        borderRadius: 12,
        background: status === "done" ? "var(--bg-2)" : "var(--surface)",
        border: "1px solid var(--line)",
        opacity: status === "cancelled" ? 0.6 : 1,
        transition: "all .15s ease",
      }}>
      {/* Checkbox or dot */}
      <button
        onClick={cycleStatus}
        title={isTask ? "Cycle: à faire → en cours → fait" : k.label}
        style={{
          width: 22, height: 22, borderRadius: 999,
          border: `1.5px solid ${isTask ? s.color : k.color}`,
          background: status === "done" ? s.color : (isTask ? "transparent" : k.bg),
          color: status === "done" ? "#fff" : (isTask ? s.color : k.color),
          display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
          cursor: isTask ? "pointer" : "default",
        }}
      >
        {isTask && status === "done" && <Icon name="check" size={12} color="#fff" strokeWidth={2.4} />}
        {isTask && status === "progress" && <span style={{ width: 8, height: 8, borderRadius: 999, background: s.color }} />}
        {!isTask && <KindIcon kind={item.kind} size={11} color={k.color} />}
      </button>

      {/* Title + meta */}
      <div className="col grow" style={{ gap: 2, minWidth: 0 }}>
        <div className="row gap-2" style={{ minWidth: 0 }}>
          <span className="truncate" style={{
            fontWeight: 500, fontSize: 14, color: "var(--ink)",
            textDecoration: status === "done" || status === "cancelled" ? "line-through" : "none",
            textDecorationColor: "var(--ink-4)",
          }}>{item.title}</span>
        </div>
        <div className="row gap-3 small muted" style={{ flexWrap: "wrap" }}>
          {!isTask && <KindChip kind={item.kind} />}
          {item.recurrence?.kind && item.recurrence.kind !== "none" && (
            <span className="row gap-1" style={{ alignItems: "center" }}>
              <Icon name="repeat" size={11} /> {recurrenceLabel(item.recurrence)}
            </span>
          )}
          {item.notify && (
            <span className="row gap-1" style={{ alignItems: "center" }}>
              <Icon name="bell" size={11} /> rappel
            </span>
          )}
          {item.assignee && (
            <span className="row gap-1" style={{ alignItems: "center" }}>
              <span style={{
                width: 16, height: 16, borderRadius: 999,
                background: USERS[item.assignee]?.color || "var(--ink-3)",
                color: "#FFF8F0", fontSize: 9, fontWeight: 700,
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                fontFamily: "var(--font-display)",
              }}>{(USERS[item.assignee]?.avatar || item.assignee[0].toUpperCase())}</span>
              {USERS[item.assignee]?.name || item.assignee}
            </span>
          )}
          {item.notes && <span className="truncate">{item.notes}</span>}
        </div>
      </div>

      {/* Right side */}
      <div className="row gap-2" style={{ flexShrink: 0 }}>
        {isTask && <StatusPill status={status} compact />}
        <PriorityFlag p={item.priority} />
        <IconButton icon="edit" label="Modifier" onClick={() => onEdit(item)} />
      </div>
    </div>
  );
}

function recurrenceLabel(r) {
  if (!r || r.kind === "none") return "Une fois";
  if (r.kind === "daily") return "Tous les jours";
  if (r.kind === "weekly") return "Chaque semaine";
  if (r.kind === "monthly") return "Chaque mois";
  if (r.kind === "custom") return `${(r.days || []).length} dates`;
  return "";
}

function DashboardView({ items, openForm, onStatusChange, onEdit, navigate, user }) {
  const today = TODAY;
  const todayItems = itemsOnDate(items, today);
  const todayTasks = todayItems.filter(x => x.kind === "task");
  const todayEvents = todayItems.filter(x => x.kind !== "task");

  // Overdue: non-recurring tasks before today, not done/cancelled
  const overdue = items.filter(x => {
    if (x.kind !== "task") return false;
    if ((x.recurrence?.kind || "none") !== "none") return false;
    if (!isBefore(fromYmd(x.date), today)) return false;
    return !["done", "cancelled"].includes(x.status);
  }).sort((a, b) => a.date.localeCompare(b.date));

  // Upcoming events (next 14 days, not today)
  const upcoming = [];
  for (let i = 1; i <= 14; i++) {
    const d = addDays(today, i);
    const its = itemsOnDate(items, d).filter(x => x.kind !== "task");
    its.forEach(it => upcoming.push({ item: it, date: d }));
  }

  // Counts
  const remainingToday = todayTasks.filter(x => ["todo", "progress"].includes(statusOn(x, today))).length;
  const doneToday = todayTasks.filter(x => statusOn(x, today) === "done").length;

  return (
    <div className="col gap-5 view-pad" style={{ maxWidth: 1280, margin: "0 auto" }}>
      <DashboardHero items={items} openForm={openForm} user={user} />

      {/* Stats grid */}
      <div className="grid-stats" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
        <StatCard icon="check" label="Aujourd'hui"   value={remainingToday} hint={`${doneToday} terminées`} accent="var(--terracotta)" bg="var(--terracotta-tint)" />
        <StatCard icon="bell"  label="En retard"     value={overdue.length} hint={overdue.length === 0 ? "Bravo, rien" : "à rattraper"} accent="var(--prio-high)" bg="#F4DDD8" />
        <StatCard icon="cake"  label="Événements"    value={upcoming.length} hint="14 prochains jours" accent="var(--event)" bg="var(--event-bg)" />
        <StatCard icon="repeat" label="Récurrentes"  value={items.filter(x => (x.recurrence?.kind || "none") !== "none").length} hint="actives" accent="var(--done)" bg="var(--done-bg)" />
      </div>

      <div className="grid-2col" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 20 }}>
        {/* Today's tasks */}
        <div className="col gap-3">
          <SectionHeading
            eyebrow="Vue principale"
            title="Tâches du jour"
            count={todayTasks.length}
            action={<Button variant="soft" icon="list" onClick={() => navigate("tasks")}>Tout voir</Button>}
          />
          <div className="col gap-2">
            {todayTasks.length === 0 ? (
              <Empty title="Aucune tâche aujourd'hui" hint="Profitez-en, ou ajoutez quelque chose." action={<Button variant="primary" icon="plus" onClick={openForm}>Nouvelle tâche</Button>} />
            ) : (
              todayTasks.map(it => <TaskRow key={it.id} item={it} date={today} onStatusChange={onStatusChange} onEdit={onEdit} />)
            )}
          </div>

          {overdue.length > 0 && (
            <>
              <div style={{ height: 8 }} />
              <SectionHeading eyebrow="À rattraper" title="En retard" count={overdue.length} />
              <div className="col gap-2">
                {overdue.slice(0, 4).map(it => <TaskRow key={it.id} item={it} date={fromYmd(it.date)} onStatusChange={onStatusChange} onEdit={onEdit} dense />)}
              </div>
            </>
          )}
        </div>

        {/* Right column */}
        <div className="col gap-5">
          <div className="col gap-3">
            <SectionHeading eyebrow="Aujourd'hui" title="Événements" count={todayEvents.length} />
            <div className="col gap-2">
              {todayEvents.length === 0 ? (
                <div className="muted small" style={{ padding: 16, background: "var(--surface)", border: "1px dashed var(--line-2)", borderRadius: 12 }}>
                  Aucun événement aujourd'hui
                </div>
              ) : (
                todayEvents.map(it => <TaskRow key={it.id} item={it} date={today} onStatusChange={onStatusChange} onEdit={onEdit} dense />)
              )}
            </div>
          </div>

          <div className="col gap-3">
            <SectionHeading eyebrow="À venir" title="Prochains événements" />
            <Card padding={0}>
              <div className="col">
                {upcoming.length === 0 ? (
                  <div style={{ padding: 20 }} className="muted small">Pas d'événement prévu</div>
                ) : (
                  upcoming.slice(0, 6).map(({ item, date }, i) => {
                    const k = KINDS[item.kind];
                    return (
                      <div key={item.id + i} className="row gap-3" style={{ padding: "12px 16px", borderTop: i === 0 ? "none" : "1px solid var(--line)" }}>
                        <div className="col" style={{ alignItems: "center", justifyContent: "center", width: 44, gap: 0 }}>
                          <div className="tiny" style={{ color: k.color }}>{DAYS_SHORT[date.getDay()].replace(".", "")}</div>
                          <div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: "var(--ink)", lineHeight: 1 }}>{date.getDate()}</div>
                        </div>
                        <div className="col grow" style={{ gap: 2, minWidth: 0 }}>
                          <div className="row gap-2"><KindChip kind={item.kind} /></div>
                          <div className="truncate" style={{ fontWeight: 500 }}>{item.title}</div>
                          {item.notes && <div className="small muted truncate">{item.notes}</div>}
                        </div>
                        <IconButton icon="chev" label="Détails" onClick={() => onEdit(item)} />
                      </div>
                    );
                  })
                )}
              </div>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardView, TaskRow, recurrenceLabel });
