// Dashboard.jsx — 4 sub-views: Overview, Worklog, Plans, People
//
// Owns the editable lists. Receives state + setters from App so persistence/
// undo can later be added at the top level.

const TOTAL_WEEKS = 14;
const WEEK_LABELS = Array.from({ length: TOTAL_WEEKS }, (_, i) => `W${i + 1}`);

// ─── Plan content helpers (backward-compat with legacy {title,kicker,body}) ───
function planTitle(plan) {
  if (plan.content !== undefined) return plan.content.split('\n')[0].trim() || "（無標題）";
  return plan.title || "（無標題）";
}
function planBody(plan) {
  if (plan.content !== undefined) {
    const nl = plan.content.indexOf('\n');
    return nl >= 0 ? plan.content.slice(nl + 1).trimStart() : "";
  }
  return [plan.kicker, plan.body].filter(Boolean).join('\n');
}
function planBodyLines(plan, n = 3) {
  return planBody(plan).split('\n').filter(l => l.trim()).slice(0, n).join(' ').trim();
}

// 已處理過的快速新增編號（元件會重新掛載，所以放在模組層）
let quickAddHandled = 0;

function Dashboard({ tab, onTabChange, quickAdd, tasks, setTasks, people, setPeople, plans, setPlans, suppliers, setSuppliers, resources, setResources }) {
  const [taskModal, setTaskModal]   = React.useState({ open: false, initial: null });
  const [personModal, setPersonModal] = React.useState({ open: false, initial: null });
  const [planModal, setPlanModal]   = React.useState({ open: false, initial: null });
  const [planDetail, setPlanDetail] = React.useState({ open: false, target: null });
  const [taskPreview, setTaskPreview] = React.useState(null);
  const [confirm, setConfirm] = React.useState(null);

  // 手機「＋」快速新增：工作日誌與計畫的新增視窗在這裡開；零件交給 PartsView
  React.useEffect(() => {
    if (!quickAdd || quickAdd.n === quickAddHandled) return;
    if (quickAdd.kind === "task") { quickAddHandled = quickAdd.n; setTaskModal({ open: true, initial: null }); }
    if (quickAdd.kind === "plan") { quickAddHandled = quickAdd.n; setPlanModal({ open: true, initial: null }); }
  }, [quickAdd]);

  // Common edit-list helpers
  const saveTask = (t) => setTasks(prev => {
    if (t.id) return prev.map(x => x.id === t.id ? { ...x, ...t } : x);
    return [...prev, { ...t, id: "t" + (Date.now()) }];
  });
  const deleteTask = (t) => setTasks(prev => prev.filter(x => x.id !== t.id));
  // 打勾／取消打勾：完成時記下時間，首頁才能算「近 7 天完成幾件」
  const toggleTask = (t) => {
    const done = t.state === "done";
    saveTask({ id: t.id, state: done ? "active" : "done", doneAt: done ? null : Date.now() });
  };
  const isMobile = useIsMobile();
  const editTask = (t) => setTaskModal({ open: true, initial: t });
  // 新增：可以先帶入欄位（月曆帶到期日、四象限帶位置）
  const newTask = (init) => setTaskModal({ open: true, initial: init && Object.keys(init).length && !init.nativeEvent
    ? { subsystem: "其他", title: "", progress: 0, start: 0, span: 1, owner: "", size: "1x1", state: "active", due: "", ...init }
    : null });

  const savePerson = (p) => setPeople(prev => {
    if (p.id) return prev.map(x => x.id === p.id ? { ...x, ...p } : x);
    return [...prev, { ...p, id: "p" + Date.now() }];
  });
  const deletePerson = (p) => setPeople(prev => prev.filter(x => x.id !== p.id));

  const savePlan = (p) => setPlans(prev => {
    if (p.id) return prev.map(x => x.id === p.id ? { ...x, ...p } : x);
    return [...prev, { ...p, id: "pl" + Date.now() }];
  });
  const deletePlan = (p) => setPlans(prev => prev.filter(x => x.id !== p.id));

  return (
    <>
      {tab === "overview" && (
        <HomeView tasks={tasks} onToggle={toggleTask} onOpen={editTask} onNew={newTask}
          onMove={(t, pos) => saveTask({ id: t.id, ...pos })}
          onNavigate={(id) => onTabChange?.(id)}/>
      )}
      {tab === "worklog" && isMobile && (
        <MobileTasks tasks={tasks} onToggle={toggleTask} onOpen={editTask} onNew={newTask}
          onDelete={(t) => setConfirm({ kind: "task", target: t })}/>
      )}
      {tab === "worklog" && !isMobile && (
        <WorklogView tasks={tasks}
          openTask={(t) => setTaskPreview(t)}
          newTask={newTask}
          onDelete={(t) => setConfirm({ kind: "task", target: t })}/>
      )}
      {(tab === "plans" || tab === "resources") && (
        <SubSwitch value={tab} onChange={onTabChange} options={[
          { id: "plans",     label: "內部資料", hint: "我們的提案" },
          { id: "resources", label: "外部資料", hint: "資源、規則、參考" },
        ]}/>
      )}
      {(tab === "parts" || tab === "specs") && (
        <SubSwitch value={tab} onChange={onTabChange} options={[
          { id: "parts", label: "零件管理", hint: "採購、供應商" },
          { id: "specs", label: "零件規格", hint: "尺寸、型號" },
        ]}/>
      )}
      {tab === "plans" && (
        <PlansView plans={plans} setPlans={setPlans}
          openPlan={(p) => setPlanDetail({ open: true, target: p })}
          editPlan={(p) => setPlanModal({ open: true, initial: p })}
          newPlan={() => setPlanModal({ open: true, initial: null })}
          onDelete={(p) => setConfirm({ kind: "plan", target: p })}/>
      )}
      {tab === "people" && (
        <PeopleView people={people}
          editPerson={(p) => setPersonModal({ open: true, initial: p })}
          newPerson={() => setPersonModal({ open: true, initial: null })}
          onDelete={(p) => setConfirm({ kind: "person", target: p })}/>
      )}
      {tab === "parts" && (
        <PartsView suppliers={suppliers} setSuppliers={setSuppliers} quickAdd={quickAdd}/>
      )}
      {tab === "specs" && <PartSpecs/>}
      {tab === "resources" && (
        <ResourcesView resources={resources} setResources={setResources}/>
      )}

      <TaskModal open={taskModal.open} initial={taskModal.initial}
        onClose={() => setTaskModal({ open: false, initial: null })}
        onSave={(t) => {
          // 在表單改了重要度／到期日，就讓四象限重新照新值擺（清掉拖曳時記的位置）
          const prev = t.id && tasks.find(x => x.id === t.id);
          if (prev && prev.priority !== t.priority) t = { ...t, imp: null };
          if (prev && prev.due !== t.due) t = { ...t, urg: null };
          saveTask(t);
        }} onDelete={deleteTask}/>
      <PersonModal open={personModal.open} initial={personModal.initial}
        onClose={() => setPersonModal({ open: false, initial: null })}
        onSave={savePerson} onDelete={deletePerson}/>
      <PlanModal open={planModal.open} initial={planModal.initial}
        onClose={() => setPlanModal({ open: false, initial: null })}
        onSave={savePlan} onDelete={deletePlan}/>

      {planDetail.open && planDetail.target && (
        <PlanPreview plan={planDetail.target} plans={plans}
          onClose={() => setPlanDetail({ open: false, target: null })}
          onEdit={(p) => { setPlanDetail({ open: false, target: null }); setPlanModal({ open: true, initial: p }); }}
          onDelete={(p) => { setPlanDetail({ open: false, target: null }); setConfirm({ kind: "plan", target: p }); }}
          onTagChange={(id, tag) => setPlans(prev => prev.map(p => p.id === id ? { ...p, tag } : p))}/>
      )}

      {taskPreview && (
        <BentoPreviewModal task={taskPreview}
          onClose={() => setTaskPreview(null)}
          onEdit={() => { setTaskModal({ open: true, initial: taskPreview }); setTaskPreview(null); }}
          onDelete={() => { setConfirm({ kind: "task", target: taskPreview }); setTaskPreview(null); }}/>
      )}

      <ConfirmDialog open={!!confirm} onClose={() => setConfirm(null)}
        title="確定刪除這筆資料？"
        body={confirm ? `「${confirm.target.title || confirm.target.name}」將被永久移除，此操作無法復原。` : ""}
        onConfirm={() => {
          if (!confirm) return;
          if (confirm.kind === "task")   deleteTask(confirm.target);
          if (confirm.kind === "person") deletePerson(confirm.target);
          if (confirm.kind === "plan")   deletePlan(confirm.target);
        }}/>
    </>
  );
}

// ═══════════════════════════════════════════════════════════
//  WORKLOG — 月曆 + Gantt + Bento；統計往上拉才出現
// ═══════════════════════════════════════════════════════════
function WorklogView({ tasks, openTask, newTask, onDelete }) {

  const [isMobile, setIsMobile] = React.useState(typeof window !== "undefined" && window.innerWidth <= 768);
  React.useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const [view, setView] = React.useState("calendar"); // calendar | gantt | bento
  const [filter, setFilter] = React.useState("all");
  const [sel, setSel] = React.useState(null);
  const [statsShown] = usePullReveal();   // 統計平常收起來，捲到頂再往上拉才出現

  const filtered = filter === "all" ? tasks : tasks.filter(t => t.subsystem === filter);
  const undated = filtered.filter(t => t.state !== "done" && !t.due).length;

  return (
    <div className="worklog-view" style={{ display: "flex", flexDirection: "column", gap: "var(--gap-zone)" }}>
      <HvStatsLine tasks={filtered} shown={statsShown}/>

      {/* Mobile: unified single glass pill — [subsystems] | [view toggle] | [+] */}
      <div className="worklog-mobile-bar">
        {/* Subsystem icon buttons */}
        {[{ id: "all", ui: "filter" }, ...SUBSYSTEMS.map(s => ({ id: s, sub: s }))].map(s => {
          const active = filter === s.id;
          return (
            <button key={s.id} onClick={() => setFilter(s.id)} title={s.id === "all" ? "全部" : s.id}
              className={active ? "seg-btn--active" : ""}
              style={{ padding: "0 9px", height: 28, borderRadius: 999, border: 0, cursor: "pointer",
                background: active ? "#fff" : "transparent", flexShrink: 0,
                color: active ? "var(--ink)" : "var(--faint)",
                boxShadow: active ? "0 1px 3px rgba(0,0,0,0.08)" : "none",
                display: "inline-flex", alignItems: "center", transition: "all .15s",
              }}>
              {s.ui ? <UIIcon kind={s.ui} size={13}/> : <SubsystemIcon kind={s.sub} size={13} color={active ? "var(--ink)" : "var(--faint)"}/>}
            </button>
          );
        })}
        {/* Separator */}
        <div style={{ width: 1, alignSelf: "stretch", background: "rgba(120,120,128,0.35)", margin: "4px 3px", flexShrink: 0 }}/>
        {/* View toggle — single button, tap to cycle */}
        <button onClick={() => setView(v => v === "calendar" ? "gantt" : v === "gantt" ? "bento" : "calendar")}
          title={view === "calendar" ? "切換排列" : view === "gantt" ? "切換堆疊" : "切換月曆"}
          className="seg-btn--active"
          style={{ padding: "0 9px", height: 28, borderRadius: 999, border: 0, cursor: "pointer",
            background: "#fff", flexShrink: 0, color: "var(--ink)",
            boxShadow: "0 1px 3px rgba(0,0,0,0.08)",
            display: "inline-flex", alignItems: "center", transition: "all .15s",
          }}>
          <UIIcon kind={view === "calendar" ? "calendar" : view === "gantt" ? "filter" : "layers"} size={13}/>
        </button>
        {/* + button */}
        <button onClick={() => newTask()} title="新增工作"
          style={{ padding: "0 10px", height: 28, borderRadius: 999, border: 0, cursor: "pointer",
            background: "transparent", color: "var(--ink)", flexShrink: 0,
            display: "inline-flex", alignItems: "center",
          }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--faint)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 5v14M5 12h14"/>
          </svg>
        </button>
      </div>

      {/* Desktop section head — hidden on mobile */}
      {!isMobile && (
        <SectionHead
          title="工作·Worklog"
          action={
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <SegmentedFilter className="subsystem-filter" value={filter} onChange={setFilter} options={[
                { id: "all",  label: "全部", uiIcon: "filter" },
                ...SUBSYSTEMS.map(s => ({ id: s, label: s, subIcon: s })),
              ]}/>
              <div style={{ width: 0.5, height: 20, background: "var(--rule)" }} />
              <SegmentedFilter className="gantt-view-toggle" value={view} onChange={setView} options={[
                { id: "calendar", label: "月曆", uiIcon: "calendar" },
                { id: "gantt", label: "排列", uiIcon: "filter" },
                { id: "bento", label: "堆疊", uiIcon: "layers" },
              ]}/>
              <div style={{ width: 0.5, height: 20, background: "var(--rule)" }} />
              <IconBtn icon="plus" onClick={() => newTask()} title="新增工作" style={{ borderRadius: 999 }} />
            </div>
          }/>
      )}

      {view === "calendar" ? (
        <div className="tcard large" style={{ padding: "18px 20px 20px" }}>
          <HvCalendar tasks={filtered} weeks={6} variant="full" sel={sel} onSel={setSel}
            onOpen={openTask} onNew={newTask}/>
          {sel && <HvAgenda tasks={filtered} sel={sel} onOpen={openTask}/>}
          <div className="hv-mono hv-cal-foot">
            雙擊日期新增{undated > 0 ? ` · 另有 ${undated} 件沒排到期日，在「排列」看` : ""}
          </div>
        </div>
      ) : view === "gantt" ? (
        <GanttChart tasks={filtered} onTaskClick={openTask} onDelete={onDelete}/>
      ) : (
        <BentoBoard tasks={filtered} onTaskClick={openTask}/>
      )}
    </div>
  );
}

// 合併分頁裡的第二層切換（零件：管理／規格；資料：內部／外部）
function SubSwitch({ value, onChange, options }) {
  return (
    <div className="sub-switch" role="tablist">
      {options.map(o => (
        <button key={o.id} role="tab" aria-selected={value === o.id}
          className={"sub-switch-btn" + (value === o.id ? " is-on" : "")}
          onClick={() => value !== o.id && onChange?.(o.id)}>
          <span className="sub-switch-label">{o.label}</span>
          {o.hint && <span className="sub-switch-hint">{o.hint}</span>}
        </button>
      ))}
    </div>
  );
}

function SegmentedFilter({ options, value, onChange, className }) {
  return (
    <div className={`seg-filter-wrap${className ? " " + className : ""}`}>
      {options.map(o => (
        <button
          key={o.id}
          className={`seg-btn${value === o.id ? " seg-btn--active" : ""}`}
          onClick={() => onChange(o.id)}
        >
          {o.uiIcon && <UIIcon kind={o.uiIcon} size={12} />}
          {o.subIcon && <SubsystemIcon kind={o.subIcon} size={12} />}
          {o.shortLabel
            ? <><span className="seg-label">{o.label}</span><span className="seg-short">{o.shortLabel}</span></>
            : <span className="seg-label">{o.label}</span>
          }
        </button>
      ))}
    </div>
  );
}

// ─── Gantt ─────────────────────────────────────────────────
function GanttChart({ tasks, onTaskClick, onDelete }) {
  const colW = 100 / TOTAL_WEEKS;
  return (
    <div className="tcard large gantt-chart" style={{ padding: "16px 0 18px", overflow: "hidden" }}>
      {/* scrollable inner — allows horizontal pan on mobile */}
      <div className="gantt-scroll" style={{
        overflowX: "auto", WebkitOverflowScrolling: "touch",
        padding: "0 14px",
      }}>
        {/* week ruler */}
        <div className="gantt-ruler" style={{ display: "flex", paddingLeft: 220, marginBottom: 8, minWidth: 560 }}>
          {WEEK_LABELS.map((w, i) => (
            <div key={w} style={{
              flex: 1, fontFamily: "var(--font-mono)", fontSize: 9,
              color: i === 4 ? "var(--accent)" : "var(--muted)",
              fontWeight: i === 4 ? 700 : 500,
              letterSpacing: "0.04em", textAlign: "left", paddingLeft: 4,
              borderLeft: "0.5px solid " + (i === 4 ? "var(--accent-mid)" : "rgba(0,0,0,0.05)"),
              position: "relative",
            }}>
              {w}
              {i === 4 && <div style={{
                position: "absolute", top: 14, left: 0, bottom: -8,
                width: 1, background: "var(--accent)", opacity: 0.5,
                pointerEvents: "none",
              }}/>}
            </div>
          ))}
        </div>

        {/* rows */}
        <div style={{ display: "flex", flexDirection: "column", gap: 6, minWidth: 560 }}>
          {tasks.map(t => (
            <GanttRow key={t.id} task={t} colW={colW}
              onClick={() => onTaskClick(t)} onDelete={() => onDelete(t)}/>
          ))}
          {tasks.length === 0 && (
            <div style={{
              padding: "30px 20px", textAlign: "center",
              color: "var(--muted)", fontSize: 12,
            }}>沒有符合的工作</div>
          )}
        </div>
      </div>
    </div>
  );
}

function GanttRow({ task, colW, onClick, onDelete }) {
  const color = SUBSYSTEM_COLOR[task.subsystem];
  const isDone = task.state === "done";
  const isFocus = task.state === "focus";
  return (
    <div onClick={onClick} style={{
      display: "flex", alignItems: "center",
      borderRadius: 8, transition: "background .15s",
      cursor: "pointer", padding: "4px 6px",
    }} onMouseEnter={e => e.currentTarget.style.background = "rgba(0,0,0,0.03)"}
       onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
      <div className="gantt-label" style={{ width: 214, display: "flex", alignItems: "center", gap: 8, paddingRight: 10 }}>
        <SubsystemIcon kind={task.subsystem} size={13} color={color}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 12.5, color: "var(--ink)", fontWeight: isFocus ? 600 : 500,
            overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
            opacity: isDone ? 0.55 : 1,
          }}>{task.title}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--muted)", marginTop: 1 }}>
            {task.owner || "—"}
          </div>
        </div>
      </div>
      <div style={{ flex: 1, position: "relative", height: 24 }}>
        {/* grid */}
        <div style={{
          position: "absolute", inset: 0, display: "flex",
        }}>
          {WEEK_LABELS.map((_, i) => (
            <div key={i} style={{
              flex: 1, borderLeft: "0.5px solid " + (i === 4 ? "var(--accent-mid)" : "rgba(0,0,0,0.04)"),
            }}/>
          ))}
        </div>
        {/* bar */}
        <div style={{
          position: "absolute",
          left: `${task.start * colW}%`,
          width: `${task.span * colW}%`,
          top: 4, bottom: 4,
          background: isFocus ? "var(--accent)" : (isDone ? color + "44" : color + "22"),
          border: "0.5px solid " + (isFocus ? "var(--accent)" : color + "55"),
          borderRadius: 6,
          display: "flex", alignItems: "center",
          padding: "0 6px",
          overflow: "hidden",
        }}>
          {/* progress fill */}
          <div style={{
            position: "absolute", left: 0, top: 0, bottom: 0,
            width: `${task.progress}%`,
            background: isFocus ? "rgba(255,255,255,0.18)" : color + "55",
            transition: "width .8s var(--ease-out)",
          }}/>
          <span style={{
            position: "relative", fontFamily: "var(--font-mono)",
            fontSize: 9, fontWeight: 700,
            color: isFocus ? "#fff" : color, letterSpacing: "0.04em",
          }}>{task.progress}%</span>
        </div>
      </div>
      <div className="gantt-row-actions" style={{ width: 60, display: "flex", justifyContent: "flex-end", gap: 0 }}>
        <IconBtn icon="edit"  onClick={(e) => { e.stopPropagation(); onClick(); }} title="編輯" size={24}/>
        <IconBtn icon="trash" onClick={(e) => { e.stopPropagation(); onDelete(); }} title="刪除" size={24} danger/>
      </div>
    </div>
  );
}

// ─── Bento Board ───────────────────────────────────────────
function BentoBoard({ tasks, onTaskClick }) {
  const [isMobile, setIsMobile] = React.useState(typeof window !== "undefined" && window.innerWidth <= 768);
  React.useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  // 將卡片依照尺寸權重排序，讓大方塊 (3x2, 2x2, 2x1) 優先繪製，從而自動往左上角排列
  const sortedTasks = React.useMemo(() => {
    const getWeight = (size) => {
      if (size === "3x2") return 6;
      if (size === "2x2") return 4;
      if (size === "2x1") return 2;
      return 1; // 1x1
    };
    return [...tasks].sort((a, b) => getWeight(b.size || "1x1") - getWeight(a.size || "1x1"));
  }, [tasks]);

  const renderCards = () => {
    const elements = [];
    let cellsUsed = 0;
    const maxCells = isMobile ? 16 : 24;

    const getCells = (size) => {
      if (isMobile) {
        if (size === "3x2") return 8;
        if (size === "2x2") return 4;
        if (size === "2x1") return 2;
        return 2;
      }
      if (size === "3x2") return 6;
      if (size === "2x2") return 4;
      if (size === "2x1") return 2;
      return 1;
    };

    // 先過濾出放得進的卡
    const visible = [];
    let used = 0;
    for (const t of sortedTasks) {
      const c = getCells(t.size || "1x1");
      if (used + c <= maxCells) { visible.push(t); used += c; }
    }

    // 把連續兩張 2x1 配對成一個 2x2 wrapper
    let i = 0;
    while (i < visible.length) {
      const t = visible[i];
      if (t.size === "2x1" && !isMobile) {
        // 往後找下一張 2x1
        const j = visible.findIndex((u, idx) => idx > i && u.size === "2x1");
        if (j !== -1) {
          const t2 = visible[j];
          // 把 j 從陣列拿走，讓它和 t 配對
          visible.splice(j, 1);
          elements.push(
            <div key={`pair-${t.id}-${t2.id}`} style={{
              gridColumn: "span 2", gridRow: "span 2",
              display: "grid",
              gridTemplateRows: "1fr 1fr",
              gap: "var(--bento-gap, var(--gap-card))",
            }}>
              <BentoCard task={t}  onClick={() => onTaskClick(t)}  paired />
              <BentoCard task={t2} onClick={() => onTaskClick(t2)} paired />
            </div>
          );
          i++;
          continue;
        }
      }
      elements.push(<BentoCard key={t.id} task={t} onClick={() => onTaskClick(t)} />);
      i++;
    }

    return elements;
  };

  return (
    <div className="bento-board" style={{
      display: "grid", gridTemplateColumns: "repeat(8, 1fr)",
      gridAutoRows: "var(--bento-row-h)", gap: "var(--bento-gap, var(--gap-card))", gridAutoFlow: "dense",
    }}>
      {renderCards()}
    </div>
  );
}

// ─── ActivityRing (供 BentoPreviewModal 使用) ───
function ActivityRing({ progress, size, strokeWidth, color }) {
  const radius = (size - strokeWidth) / 2;
  const circumference = radius * 2 * Math.PI;
  const offset = circumference - (Math.min(progress, 100) / 100) * circumference;
  
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: "rotate(-90deg)", display: "block" }}>
      <circle
        cx={size / 2} cy={size / 2} r={radius}
        fill="none"
        stroke="currentColor"
        strokeWidth={strokeWidth}
        style={{ opacity: 0.1, color: color }}
      />
      <circle
        cx={size / 2} cy={size / 2} r={radius}
        fill="none"
        stroke={color}
        strokeWidth={strokeWidth}
        strokeLinecap="round"
        strokeDasharray={circumference}
        strokeDashoffset={offset}
        style={{ transition: "stroke-dashoffset 0.8s var(--ease-out)" }}
      />
    </svg>
  );
}

function BentoCard({ task, onClick }) {
  const { subsystem, title, progress, start, span, size = "1x1", state, owner } = task;
  const isFocus = state === "focus";
  const isDone  = state === "done";
  const isLarge = size === "2x2" || size === "3x2";

  const sizeStyle = {
    "1x1": { gridColumn: "span 1", gridRow: "span 1" },
    "2x1": { gridColumn: "span 2", gridRow: "span 1" },
    "2x2": { gridColumn: "span 2", gridRow: "span 2" },
    "3x2": { gridColumn: "span 3", gridRow: "span 2" },
  }[size];

  const daysToEnd = start + span - 5;
  const daysLabel = daysToEnd === 0 ? "TODAY"
                  : daysToEnd < 0  ? `OVERDUE ${-daysToEnd}W` : `T-${daysToEnd}W`;

  const subColor   = window.SUBSYSTEM_COLOR?.[subsystem] || "var(--blue)";
  const textColor  = isFocus ? "#fff" : "var(--ink)";
  const mutedColor = isFocus ? "rgba(255,255,255,0.55)" : "var(--muted)";

  // 簡化：只用 2 種環色 — 完成=綠，其他=藍（focus 卡用半透明白）
  const ringColor = isFocus ? "rgba(255,255,255,0.85)"
                  : isDone  ? "var(--green)"
                  : "var(--blue)";

  return (
    <div onClick={onClick} className={`tcard large hoverable bento-card-${size || "1x1"}`} style={{
      ...sizeStyle,
      /* 非大卡：左 padding 壓縮讓圈靠近邊界；大卡維持對稱 */
      padding: isLarge ? "14px 16px" : "10px 14px 10px 10px",
      cursor: "pointer", overflow: "hidden",
      display: "flex", flexDirection: "column",
      background: isFocus ? "var(--accent)" : "var(--card-fill)",
      borderColor: isFocus ? "var(--accent)" : undefined,
      opacity: isDone ? 0.7 : 1,
    }}>

      {isLarge ? (
        /* ══ LARGE (2x2 / 3x2)：大數字 + 名稱 + 條 + 時間 — 保持不變 ══ */
        <>
          <span style={{
            width: 6, height: 6, borderRadius: 99,
            background: isFocus ? "rgba(255,255,255,0.7)" : subColor,
            display: "inline-block",
          }}/>
          <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "flex-end", gap: 5, marginTop: 8 }}>
            <DisplayNumber value={progress} unit="%" size={44} color={textColor}/>
            <div style={{
              fontWeight: 700, lineHeight: 1.25, letterSpacing: "-0.01em",
              color: textColor, fontSize: 15,
              display: "-webkit-box", WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical", overflow: "hidden",
            }}>{title}</div>
            <ProgressBar value={progress} height={2} dark={isFocus}/>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 8, letterSpacing: "0.04em", color: mutedColor, display: "flex", justifyContent: "space-between" }}>
              <span>{daysLabel}</span><span>{owner}</span>
            </div>
          </div>
        </>
      ) : (
        /* ══ SMALL / WIDE (1x1 / 2x1)：進度圈 + 名稱/時間
              Apple Control Center widget 排版:
              [ 圈 ]  名稱（粗體，2行）
                      T-xW（小字）
        ══ */
        <div style={{ display: "flex", alignItems: "center", gap: 12, height: "100%" }}>

          {/* ── 左：ActivityRing，數字在圈心（大字） ── */}
          <div style={{ position: "relative", flexShrink: 0 }}>
            <ActivityRing
              progress={progress}
              size={48}
              strokeWidth={4.5}
              color={ringColor}
            />
            <div style={{
              position: "absolute", inset: 0,
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <span style={{
                fontFamily: "var(--display-family)", fontWeight: 700,
                fontSize: 18, lineHeight: 1, letterSpacing: "-0.03em",
                color: textColor,
              }}>{progress}</span>
            </div>
          </div>

          {/* ── 右：名稱（主角）＋ 剩餘天數 ── */}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontWeight: 700, lineHeight: 1.28, letterSpacing: "-0.01em",
              color: textColor, fontSize: 13,
              display: "-webkit-box",
              WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical", overflow: "hidden",
            }}>{title}</div>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 9,
              letterSpacing: "0.04em", color: mutedColor,
              marginTop: 4,
            }}>{daysLabel}</div>
          </div>

        </div>
      )}
    </div>
  );
}

// ─── BentoPreviewModal (簡覽) ───
const TASK_STATE_LABEL = { focus: "本週焦點", done: "已完成", active: "進行中" };

function BentoPreviewModal({ task, onClose, onEdit, onDelete }) {
  if (!task) return null;
  const color = window.SUBSYSTEM_COLOR?.[task.subsystem] || "var(--blue)";
  const stateLabel = TASK_STATE_LABEL[task.state] || "進行中";
  const daysToEnd = (task.start || 0) + (task.span || 0) - 5;
  const schedule = daysToEnd === 0 ? "本週到期"
    : daysToEnd < 0 ? `已逾期 ${-daysToEnd} 週` : `剩 ${daysToEnd} 週`;
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 768;
  const ringSize = isMobile ? 88 : 140;
  const ringStroke = isMobile ? 10 : 16;
  const ringFont = isMobile ? 28 : 36;

  return (
    <CardPreview
      onClose={onClose}
      color={color}
      title={task.title}
      subsystem={task.subsystem}
      node={
        <div style={{ position: "relative", width: ringSize, height: ringSize }}>
          <ActivityRing progress={task.progress || 0} size={ringSize} strokeWidth={ringStroke} color={color} />
          <div style={{
            position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center",
            fontFamily: "var(--font-sans)", fontWeight: 900, fontSize: ringFont, letterSpacing: "-0.04em",
            color: "var(--ink)",
          }}>
            {task.progress || 0}%
          </div>
        </div>
      }
      badges={
        <span style={{
          fontSize: 14, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase",
          color: color,
        }}>
          {task.subsystem}
        </span>
      }
      meta={[
        { label: "負責人", value: task.owner || "—" },
        { label: "期程", value: `W${task.start} – W${(task.start || 0) + (task.span || 0)} · ${schedule}` },
        { label: "狀態", value: stateLabel }
      ]}
      actions={<>
        {onDelete && <IconBtn danger icon="trash" style={{ marginRight: "auto" }} onClick={() => onDelete(task)} title="刪除" />}
        {onEdit && <IconBtn icon="edit" onClick={() => onEdit(task)} title="編輯" />}
      </>}
    />
  );
}

// ═══════════════════════════════════════════════════════════
//  PLANS — IG-style gallery + lightbox + detail popup + Kanban
// ═══════════════════════════════════════════════════════════
const PLAN_TAGS = ["計畫中", "進行中", "已完成", "擱置"];
const PLAN_TAG_COLORS = {
  "計畫中": "#0071e3",
  "進行中": "#b83025",
  "已完成": "#2a6b38",
  "擱置": "#86868b",
};

function PlansView({ plans, setPlans, openPlan, editPlan, newPlan, onDelete }) {
  const [view, setView] = React.useState("gallery"); // gallery | kanban
  const [drag, setDrag] = React.useState(null);
  const [over, setOver] = React.useState(null);
  const [kanbanDraggedId, setKanbanDraggedId] = React.useState(null);
  const [lightboxId, setLightboxId] = React.useState(null); // open lightbox for this plan
  
  const [isMobile, setIsMobile] = React.useState(typeof window !== "undefined" && window.innerWidth <= 768);
  React.useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const [filter, setFilter] = React.useState("全部");

  // Blueprint sorting handlers
  const onDragStart = (id) => () => setDrag(id);
  const onDragOver  = (id) => (e) => { e.preventDefault(); setOver(id); };
  const onDragEnd   = () => { setDrag(null); setOver(null); };
  const onDrop      = (id) => (e) => {
    e.preventDefault();
    if (!drag || drag === id) return;
    setPlans(prev => {
      const next = [...prev];
      const fromIdx = next.findIndex(p => p.id === drag);
      const toIdx   = next.findIndex(p => p.id === id);
      if (fromIdx < 0 || toIdx < 0) return prev;
      const [moved] = next.splice(fromIdx, 1);
      next.splice(toIdx, 0, moved);
      return next;
    });
    setDrag(null); setOver(null);
  };

  const onScaleChange = (id, newScale) => {
    setPlans(prev => prev.map(p => p.id === id ? { ...p, scale: newScale } : p));
  };

  // Kanban Column DnD
  const onKanbanDragStart = (id) => (e) => {
    setKanbanDraggedId(id);
    e.dataTransfer.setData("text/plain", id);
  };
  
  const onKanbanDropColumn = (targetTag) => (e) => {
    e.preventDefault();
    if (!kanbanDraggedId) return;
    setPlans(prev => prev.map(p => p.id === kanbanDraggedId ? { ...p, tag: targetTag } : p));
    setKanbanDraggedId(null);
  };

  const onKanbanDragOver = (e) => {
    e.preventDefault();
  };

  // KPI Calculations
  const total = plans.length;
  const inProgress = plans.filter(p => p.tag === "進行中").length;
  const completed = plans.filter(p => p.tag === "已完成").length;
  const pending = plans.filter(p => !p.tag || ["計畫中", "擱置"].includes(p.tag)).length;

  // Filtering
  const filteredPlans = filter === "全部"
    ? plans
    : plans.filter(p => {
        const currentTag = p.tag || "計畫中";
        return currentTag === filter;
      });

  // Lightbox helpers
  const lbIdx  = plans.findIndex(p => p.id === lightboxId);
  const lbPlan = plans[lbIdx] || null;
  const lbPrev = () => setLightboxId(plans[(lbIdx - 1 + plans.length) % plans.length]?.id);
  const lbNext = () => setLightboxId(plans[(lbIdx + 1) % plans.length]?.id);
  const openLightbox = (id) => setLightboxId(id);
  const closeLightbox = () => setLightboxId(null);

  return (
    <>
    <div className="plans-view" style={{ display: "flex", flexDirection: "column", gap: "var(--gap-zone)" }}>
      {/* KPI row — mobile: 一列壓縮 via .kpi-strip */}
      <div className="kpi-strip" style={{ display: "flex", gap: "var(--gap-card)" }}>
        <KPI label="PROPOSALS" value={total} foot="提案總數" />
        <KPI label="IN PROGRESS" value={inProgress} foot="進行中" />
        <KPI label="COMPLETED" value={completed} foot="已完成" />
        <KPI label="PENDING" value={pending} foot="待計畫" />
      </div>

      {/* Mobile unified single glass pill bar — [status filters] | [view toggle] | [+] */}
      {isMobile && (
        <div className="plans-mobile-bar" style={{
          display: "inline-flex", alignItems: "center", alignSelf: "flex-end",
          gap: 0, padding: 2, background: "rgba(120,120,128,0.16)",
          borderRadius: 999, height: 32, overflowX: "auto", scrollbarWidth: "none", maxWidth: "100%"
        }}>
          {["全部", ...PLAN_TAGS].map(tag => {
            const active = filter === tag;
            return (
              <button key={tag} className={active ? "seg-btn--active" : ""} onClick={() => setFilter(tag)}
                style={{
                  padding: "0 10px", height: 28, borderRadius: 999, border: 0, cursor: "pointer",
                  background: active ? "#fff" : "transparent", flexShrink: 0,
                  color: active ? "var(--ink)" : "var(--faint)",
                  fontSize: 12, fontWeight: active ? 600 : 400,
                  display: "inline-flex", alignItems: "center", transition: "all .15s",
                }}>
                <span>{tag}</span>
              </button>
            );
          })}

          {/* Separator */}
          <div style={{ width: 1, alignSelf: "stretch", background: "rgba(120,120,128,0.35)", margin: "4px 3px", flexShrink: 0 }}/>

          {/* View Toggle */}
          <button onClick={() => setView(v => v === "gallery" ? "kanban" : "gallery")}
            className="seg-btn--active"
            title={view === "gallery" ? "切換看板" : "切換圖片牆"}
            style={{
              padding: "0 9px", height: 28, borderRadius: 999, border: 0, cursor: "pointer",
              background: "#fff", flexShrink: 0, color: "var(--faint)",
              display: "inline-flex", alignItems: "center", transition: "all .15s",
            }}>
            {view === "gallery" ? (
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="7" height="7" rx="1" fill="none"/><rect x="14" y="3" width="7" height="7" rx="1" fill="none"/>
                <rect x="3" y="14" width="7" height="7" rx="1" fill="none"/><rect x="14" y="14" width="7" height="7" rx="1" fill="none"/>
              </svg>
            ) : (
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="5" height="18" rx="1" fill="none"/>
                <rect x="10" y="3" width="5" height="13" rx="1" fill="none"/>
                <rect x="17" y="3" width="5" height="9" rx="1" fill="none"/>
              </svg>
            )}
          </button>

          {/* Add Button */}
          <button onClick={newPlan} title="新增計畫"
            style={{
              padding: "0 10px", height: 28, borderRadius: 999, border: 0, cursor: "pointer",
              background: "transparent", color: "var(--ink)", flexShrink: 0,
              display: "inline-flex", alignItems: "center",
            }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--faint)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 5v14M5 12h14"/>
            </svg>
          </button>
        </div>
      )}

      {!isMobile && (
        <SectionHead
          title="提案·Plans"
          action={
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <SegmentedFilter className="status-filter" value={filter} onChange={setFilter} options={
                [{ id: "全部", label: "全部" }, ...PLAN_TAGS.map(tag => ({ id: tag, label: tag }))]
              }/>
              <div style={{ width: 0.5, height: 20, background: "var(--rule)" }} />
              <SegmentedFilter className="view-toggle" value={view} onChange={setView} options={[
                { id: "gallery", label: "堆疊", uiIcon: "layers" },
                { id: "kanban", label: "排列", uiIcon: "filter" },
              ]}/>
              <div style={{ width: 0.5, height: 20, background: "var(--rule)" }} />
              <IconBtn icon="plus" onClick={newPlan} title="新增計畫" style={{ borderRadius: 999 }} />
            </div>
          }/>
      )}

      {view === "gallery" ? (
        /* IG-style photo grid — tight 3px gap, square thumbs */
        <div style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "repeat(2, 1fr)" : "repeat(auto-fill, minmax(220px, 1fr))",
          gap: "var(--gap-zone)",
        }}>
          {filteredPlans.map(p => (
            <PlanThumb key={p.id} plan={p}
              dragging={drag === p.id}
              dragOver={over === p.id && drag !== p.id}
              draggable
              onDragStart={onDragStart(p.id)}
              onDragOver={onDragOver(p.id)}
              onDragEnd={onDragEnd}
              onDrop={onDrop(p.id)}
              onClick={() => openLightbox(p.id)}/>
          ))}
        </div>
      ) : (
        /* 工作流看板 */
        <div style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "1fr" : "repeat(4, 1fr)",
          gap: 12,
          alignItems: "start",
          minHeight: 460,
        }}>
          {PLAN_TAGS.filter(tag => !isMobile || tag === filter).map(columnTag => {
            const columnPlans = plans.filter(p => {
              const currentTag = p.tag || "計畫中";
              return currentTag === columnTag;
            });
            const tagColor = PLAN_TAG_COLORS[columnTag];
            return (
              <div
                key={columnTag}
                onDragOver={onKanbanDragOver}
                onDrop={onKanbanDropColumn(columnTag)}
                className="tcard"
                style={{
                  padding: 12,
                  display: "flex",
                  flexDirection: "column",
                  gap: 10,
                  minHeight: 400,
                  background: kanbanDraggedId ? "rgba(0, 0, 0, 0.015)" : "var(--card-fill)",
                  border: "1px solid rgba(0,0,0,0.04)",
                  transition: "background 0.2s ease",
                }}
              >
                <div style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  paddingBottom: 8,
                  borderBottom: `2.5px solid ${tagColor}40`,
                  marginBottom: 4,
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{ width: 8, height: 8, borderRadius: "50%", background: tagColor }} />
                    <span style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)" }}>{columnTag}</span>
                  </div>
                  <span className="eyebrow" style={{ color: tagColor, fontSize: 10 }}>{columnPlans.length}</span>
                </div>
                
                {columnPlans.map(p => (
                  <KanbanPlanCard
                    key={p.id}
                    plan={p}
                    onDragStart={onKanbanDragStart(p.id)}
                    onClick={() => openPlan(p)}
                  />
                ))}
                
                {columnPlans.length === 0 && (
                  <div style={{
                    padding: "36px 12px",
                    textAlign: "center",
                    color: "var(--muted)",
                    fontSize: 10,
                    fontFamily: "var(--font-mono)",
                    letterSpacing: "0.06em",
                    border: "1px dashed var(--rule)",
                    borderRadius: 8,
                  }}>
                    EMPTY
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>

    {/* 放大預覽 — 統一 DetailPreview，畫廊含上下張切換 */}
    {lightboxId && lbPlan && (
      <PlanPreview
        plan={lbPlan} plans={plans}
        onClose={closeLightbox}
        onPrev={lbPrev} onNext={lbNext}
        onEdit={() => { closeLightbox(); editPlan(lbPlan); }}
        onDelete={() => { closeLightbox(); onDelete(lbPlan); }}
        onTagChange={(id, tag) => setPlans(prev => prev.map(p => p.id === id ? { ...p, tag } : p))}
      />
    )}
    </>
  );
}

// ─── PlanThumb — compact IG-style square card ───
function PlanThumb({ plan, draggable, dragging, dragOver, onDragStart, onDragOver, onDragEnd, onDrop, onClick }) {
  const color = SUBSYSTEM_COLOR[plan.sub] || "var(--accent)";
  const tagColor = PLAN_TAG_COLORS[plan.tag] || null;
  const [hov, setHov] = React.useState(false);
  return (
    <div
      className="tcard large hoverable"
      draggable={draggable}
      onDragStart={onDragStart}
      onDragOver={onDragOver}
      onDragEnd={onDragEnd}
      onDrop={onDrop}
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        aspectRatio: "1 / 1",
        position: "relative",
        overflow: "hidden",
        cursor: "pointer",
        outline: dragOver ? "3px solid var(--accent)" : "none",
        outlineOffset: -3,
        background: plan.cover
          ? `url('${plan.cover}') center/cover`
          : `linear-gradient(135deg, ${color}cc, ${color}55)`,
      }}
    >

      {/* Hover overlay */}
      <div style={{
        position: "absolute", inset: 0, zIndex: 3,
        background: hov ? "rgba(0,0,0,0.52)" : "rgba(0,0,0,0)",
        transition: "background 0.22s ease",
        display: "flex", flexDirection: "column",
        justifyContent: "flex-end", padding: 14, gap: 4,
      }}>
        {hov && <>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 5,
            padding: "2px 7px", borderRadius: 6,
            background: color + "cc", color: "#fff",
            fontSize: 9, fontWeight: 700, fontFamily: "var(--font-mono)",
            letterSpacing: "0.08em", width: "fit-content",
          }}>
            <SubsystemIcon kind={plan.sub} size={9} color="#fff"/>{plan.sub}
          </div>
          <div style={{
            color: "#fff", fontSize: 13.5, fontWeight: 700,
            lineHeight: 1.25, letterSpacing: "-0.01em",
            overflow: "hidden", display: "-webkit-box",
            WebkitLineClamp: 2, WebkitBoxOrient: "vertical",
          }}>{planTitle(plan)}</div>
        </>}
      </div>

      {/* Status dot (always visible, top-right) */}
      {plan.tag && tagColor && (
        <div style={{
          position: "absolute", top: 10, right: 10, zIndex: 4,
          width: 8, height: 8, borderRadius: "50%",
          background: tagColor,
          boxShadow: `0 0 0 2px rgba(255,255,255,0.8)`,
        }}/>
      )}

      {/* Drag ghost (only on hover) */}
      {hov && (
        <div style={{
          position: "absolute", top: 10, left: 10, zIndex: 4,
          width: 22, height: 22, borderRadius: 6,
          background: "rgba(255,255,255,0.22)", backdropFilter: "blur(6px)",
          display: "flex", alignItems: "center", justifyContent: "center", color: "#fff",
        }}>
          <UIIcon kind="grip" size={11}/>
        </div>
      )}
    </div>
  );
}

// ─── PlanPreview — 點開提案：直接看內容；狀態、編輯、刪除收在「⋯」裡 ───
// 有附件網頁（plan.doc，例：tools/frame-sketch.html）的提案，點開就是全螢幕的附件本身
function PlanPreview({ plan, plans, onClose, onPrev, onNext, onEdit, onDelete, onTagChange }) {
  const [manage, setManage] = React.useState(false);
  React.useEffect(() => setManage(false), [plan?.id]);
  if (!plan) return null;
  const color = SUBSYSTEM_COLOR[plan.sub] || "var(--blue)";
  const idx = plans ? plans.findIndex(p => p.id === plan.id) : -1;
  const counter = idx >= 0 && plans.length > 1 ? `${idx + 1} / ${plans.length}` : undefined;
  const panel = manage && <PlanManage plan={plan} onTagChange={onTagChange} onEdit={onEdit} onDelete={onDelete}/>;

  const body = planBody(plan);
  return (
    <PlanDocViewer src={plan.doc} title={planTitle(plan)} counter={counter}
      onClose={onClose} onPrev={onPrev} onNext={onNext}
      manage={manage} onToggleManage={() => setManage(m => !m)} panel={panel}>
      {/* 沒有附件網頁：顯示完整封面圖；連封面都沒有就顯示文字 */}
      {plan.cover
        ? <img src={plan.cover} alt={planTitle(plan)} style={{ display: "block", width: "100%", height: "auto" }}/>
        : <div style={{ padding: "8px 24px 28px" }}>
            <div style={{ fontSize: 22, fontWeight: 700, marginBottom: 10 }}>{planTitle(plan)}</div>
            {body && <div style={{ fontSize: 15, lineHeight: 1.7, whiteSpace: "pre-wrap", color: "var(--label-secondary)" }}>{body}</div>}
          </div>}
    </PlanDocViewer>
  );
}

function MoreToggle({ on, onClick, light }) {
  return (
    <button onClick={onClick} title={on ? "收起" : "狀態、編輯、刪除"}
      style={{ all: "unset", cursor: "pointer", fontSize: 13, padding: "4px 10px", borderRadius: "var(--radius-full)",
        color: light ? "var(--label-primary)" : "var(--label-secondary)",
        background: on ? "var(--fill-secondary)" : "transparent" }}>
      {on ? "收起" : "⋯ 管理"}
    </button>
  );
}

// 收起來的管理區：狀態、編輯、刪除
function PlanManage({ plan, onTagChange, onEdit, onDelete }) {
  return (
    <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 12 }}>
      {onTagChange && (
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center" }}>
          <span style={{ fontSize: 12, color: "var(--label-tertiary)", marginRight: 4 }}>狀態</span>
          {PLAN_TAGS.map(tag => {
            const tc = PLAN_TAG_COLORS[tag];
            const active = plan.tag === tag;
            return (
              <button key={tag} onClick={() => onTagChange(plan.id, tag)}
                style={{
                  padding: "4px 11px", borderRadius: "var(--radius-full)", cursor: "pointer",
                  border: active ? "none" : "0.5px solid var(--separator)",
                  background: active ? tc : "transparent",
                  color: active ? "#fff" : "var(--label-secondary)",
                  fontSize: 12, fontWeight: 600, fontFamily: "var(--font-sans)",
                }}>{tag}</button>
            );
          })}
        </div>
      )}
      <div style={{ display: "flex", gap: 8 }}>
        {onEdit && <Button icon="edit" onClick={() => onEdit(plan)}>編輯</Button>}
        {onDelete && <Button variant="danger" icon="trash" onClick={() => onDelete(plan)}>刪除</Button>}
      </div>
    </div>
  );
}

// 提案彈出視窗：中間一張完整的附件（或封面圖），其餘地方模糊；點外面或 Esc 關閉
function PlanDocViewer({ src, title, counter, onClose, onPrev, onNext, manage, onToggleManage, panel, children }) {
  const frameRef = React.useRef(null);
  const [h, setH] = React.useState(600);
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose?.();
      if (e.key === "ArrowLeft")  onPrev?.();
      if (e.key === "ArrowRight") onNext?.();
    };
    const fit = () => { try { setH(frameRef.current.contentDocument.documentElement.scrollHeight); } catch {} };
    document.addEventListener("keydown", onKey);
    window.addEventListener("resize", fit);
    return () => { document.removeEventListener("keydown", onKey); window.removeEventListener("resize", fit); };
  }, [onClose, onPrev, onNext]);
  const onLoad = (e) => {
    const value = document.documentElement.dataset.appearance === "dark" ? "dark" : "light";
    try { e.target.contentWindow.postMessage({ type: "appearance", value }, location.origin); } catch {}
    // 同網域的頁面量得到高度，整張一次顯示，不出現內層捲軸；外部網址就固定高度
    const fit = () => { try { setH(e.target.contentDocument.documentElement.scrollHeight); } catch {} };
    fit(); setTimeout(fit, 300);
  };
  const btn = (label, fn, t, size = 15) => fn && (
    <button onClick={(e) => { e.stopPropagation(); fn(); }} title={t}
      style={{ all: "unset", cursor: "pointer", padding: "4px 8px", fontSize: size, color: "var(--label-secondary)" }}>{label}</button>
  );
  return ReactDOM.createPortal(
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 700, overflowY: "auto",
      background: "rgba(0,0,0,0.35)", backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)",
      padding: "40px max(16px, 4vw)", boxSizing: "border-box" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: 1180, margin: "0 auto",
        background: "var(--bg-secondary, var(--bg-primary))", borderRadius: 16, overflow: "hidden",
        boxShadow: "0 24px 80px rgba(0,0,0,0.45)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "6px 10px 6px 18px" }}>
          <span style={{ fontSize: 14, fontWeight: 600, flex: 1, minWidth: 0, overflow: "hidden",
            textOverflow: "ellipsis", whiteSpace: "nowrap", color: "var(--label-secondary)" }}>{title}</span>
          {btn("‹", onPrev, "上一個 (←)", 18)}
          {(onPrev || onNext) && counter && <span style={{ fontSize: 12, color: "var(--label-tertiary)", fontFamily: "var(--font-mono)" }}>{counter}</span>}
          {btn("›", onNext, "下一個 (→)", 18)}
          <MoreToggle on={manage} onClick={onToggleManage}/>
          {btn("✕", onClose, "關閉 (Esc)", 17)}
        </div>
        {panel && <div style={{ padding: "0 18px 12px" }}>{panel}</div>}
        {src ? <iframe ref={frameRef} key={src} src={src} title={title} onLoad={onLoad}
          style={{ width: "100%", height: h, border: "none", display: "block" }}/> : children}
      </div>
    </div>,
    document.body
  );
}

function PlanCard({ plan, draggable, dragging, dragOver, onDragStart, onDragOver, onDragEnd, onDrop, onClick, onDelete, onScaleChange }) {
  const layout = plan.layout === "portrait" || plan.layout === "a4" ? "portrait" : "landscape";
  const color = SUBSYSTEM_COLOR[plan.sub] || "var(--accent)";
  const maxScale = layout === "portrait" ? 2 : 3;
  const minScale = layout === "portrait" ? 1 : 2;
  const scale = plan.scale || minScale;
  
  return (
    <div
      draggable={draggable}
      onDragStart={onDragStart}
      onDragOver={onDragOver}
      onDragEnd={onDragEnd}
      onDrop={onDrop}
      onClick={onClick}
      className={`tcard hoverable large ${dragging ? "dragging" : ""} ${dragOver ? "drag-over" : ""}`}
      style={{
        cursor: "pointer",
        overflow: "hidden",
        position: "relative",
        outline: dragOver ? "2px solid var(--accent)" : "none",
        outlineOffset: -2,
        gridColumn: `span ${scale}`,
        aspectRatio: layout === "portrait" ? "1 / 1.414" : "1.414 / 1",
        display: "flex",
        flexDirection: "column",
        minWidth: 0,
      }}
      onMouseEnter={(e) => {
        const img = e.currentTarget.querySelector(".plan-cover-img");
        if (img) img.style.transform = "scale(1.05)";
        const handle = e.currentTarget.querySelector(".resize-handle");
        if (handle) {
          handle.style.opacity = "1";
          handle.style.transform = "none";
        }
      }}
      onMouseLeave={(e) => {
        const img = e.currentTarget.querySelector(".plan-cover-img");
        if (img) img.style.transform = "none";
        const handle = e.currentTarget.querySelector(".resize-handle");
        if (handle) {
          handle.style.opacity = "0";
          handle.style.transform = "translateY(4px)";
        }
      }}
    >
      {/* 1. Background image or blueprint */}
      {plan.cover ? (
        <>
          <div
            className="plan-cover-img"
            style={{
              position: "absolute",
              inset: 0,
              backgroundImage: `url('${plan.cover}')`,
              backgroundSize: "cover",
              backgroundPosition: "center",
              transition: "transform 0.5s cubic-bezier(0.16, 1, 0.3, 1)",
              zIndex: 1,
            }}
          />
          {/* Deep gradient protection for text readability */}
          <div
            style={{
              position: "absolute",
              inset: 0,
              background: "linear-gradient(180deg, rgba(0,0,0,0.15) 0%, rgba(0,0,0,0.25) 45%, rgba(0,0,0,0.88) 100%)",
              zIndex: 2,
              pointerEvents: "none",
            }}
          />
        </>
      ) : (
        <div
          style={{
            position: "absolute",
            inset: 0,
            background: `
              radial-gradient(circle at 100% 100%, ${color}1e 0%, transparent 60%),
              linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px),
              linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px),
              linear-gradient(rgba(255,255,255,0.01) 1px, transparent 1px),
              linear-gradient(90deg, rgba(255,255,255,0.01) 1px, transparent 1px),
              linear-gradient(135deg, #0b1a30, #040a14)
            `,
            backgroundSize: "100% 100%, 40px 40px, 40px 40px, 10px 10px, 10px 10px, 100% 100%",
            zIndex: 1,
          }}
        >
          {/* Technical drafting grid borders */}
          <div style={{
            position: "absolute",
            border: "1px dashed rgba(255,255,255,0.06)",
            inset: 12,
            borderRadius: 8,
            pointerEvents: "none",
          }} />
          
          {/* Technical labels in the background */}
          <div style={{
            position: "absolute",
            top: 50,
            left: 18,
            fontFamily: "var(--font-mono)",
            fontSize: layout === "portrait" ? 36 : 48,
            fontWeight: 900,
            color: "rgba(255, 255, 255, 0.015)",
            letterSpacing: "0.1em",
            transform: "rotate(-8deg)",
            pointerEvents: "none",
            userSelect: "none",
            whiteSpace: "nowrap",
          }}>
            {plan.sub} SECTION
          </div>

          <div style={{
            position: "absolute",
            top: 18,
            right: 18,
            fontFamily: "var(--font-mono)",
            fontSize: 7,
            color: "rgba(255, 255, 255, 0.25)",
            letterSpacing: "0.08em",
            pointerEvents: "none",
          }}>
            A4_SPEC_SYS_{plan.sub.toUpperCase()}
          </div>
        </div>
      )}

      {/* 2. Top-left drag handle and Subsystem Tag */}
      <div style={{
        position: "absolute",
        top: 12,
        left: 12,
        display: "flex",
        gap: 6,
        alignItems: "center",
        zIndex: 3,
      }}>
        <span className="drag-handle" style={{
          width: 24,
          height: 24,
          borderRadius: 6,
          background: "rgba(255,255,255,0.12)",
          backdropFilter: "blur(8px)",
          WebkitBackdropFilter: "blur(8px)",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          color: "rgba(255,255,255,0.8)",
          border: "1px solid rgba(255,255,255,0.1)",
          cursor: "grab",
        }}>
          <UIIcon kind="grip" size={12}/>
        </span>
        <SubsystemTag kind={plan.sub}/>
        {plan.tag && (
          <span style={{
            display: "inline-flex",
            padding: "2px 7px",
            borderRadius: 6,
            background: PLAN_TAG_COLORS[plan.tag] + "cc",
            color: "#ffffff",
            fontSize: 9,
            fontWeight: 700,
            fontFamily: "var(--font-sans)",
            backdropFilter: "blur(4px)",
            WebkitBackdropFilter: "blur(4px)",
            boxShadow: "0 1px 3px rgba(0,0,0,0.1)"
          }}>
            {plan.tag}
          </span>
        )}
      </div>

      {/* 3. Top-right actions */}
      <div style={{
        position: "absolute",
        top: 12,
        right: 12,
        display: "flex",
        gap: 6,
        zIndex: 3,
      }}>
        <IconBtn icon="edit" size={26} onClick={(e) => { e.stopPropagation(); onClick(); }}/>
        <IconBtn icon="trash" size={26} danger onClick={(e) => { e.stopPropagation(); onDelete(); }}/>
      </div>

      {/* 4. Bottom Glassmorphism Title Panel */}
      <div style={{
        position: "absolute",
        bottom: 0,
        left: 0,
        right: 0,
        padding: "16px 18px",
        zIndex: 3,
        background: "linear-gradient(180deg, rgba(10,15,30,0) 0%, rgba(10,15,30,0.65) 30%, rgba(10,15,30,0.92) 100%)",
        backdropFilter: "blur(6px)",
        WebkitBackdropFilter: "blur(6px)",
        borderTop: "1px solid rgba(255,255,255,0.05)",
        display: "flex",
        flexDirection: "column",
        gap: 4,
      }}>
        <div style={{
          fontFamily: "var(--display-family)",
          fontSize: layout === "portrait" ? 17 : 19,
          fontWeight: 700,
          letterSpacing: "-0.015em",
          lineHeight: 1.25,
          color: "#ffffff",
        }}>
          {planTitle(plan)}
        </div>
        <div style={{
          fontSize: 12,
          color: "rgba(255,255,255,0.65)",
          marginTop: 4,
          lineHeight: 1.45,
          textWrap: "pretty", WebkitTextWrap: "pretty",
          display: "-webkit-box",
          WebkitLineClamp: layout === "portrait" ? 3 : 2,
          WebkitBoxOrient: "vertical",
          overflow: "hidden",
        }}>
          {planBodyLines(plan, layout === "portrait" ? 3 : 2)}
        </div>
      </div>

      {/* 5. Bottom-Right Dynamic Scale Controller (Revealed on hover) */}
      <div 
        className="resize-handle"
        style={{
          position: "absolute",
          bottom: 12,
          right: 12,
          zIndex: 4,
          opacity: 0,
          transform: "translateY(4px)",
          transition: "opacity 0.25s ease, transform 0.25s ease",
        }}
      >
        <span 
          onClick={(e) => {
            e.stopPropagation();
            const nextScale = layout === "portrait" 
              ? (scale === 1 ? 2 : 1) 
              : (scale === 2 ? 3 : (scale === 3 ? 1 : 2));
            onScaleChange(plan.id, nextScale);
          }}
          style={{
            width: 26,
            height: 26,
            borderRadius: 6,
            background: "rgba(255, 255, 255, 0.12)",
            backdropFilter: "blur(8px)",
            WebkitBackdropFilter: "blur(8px)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: "#ffffff",
            border: "1px solid rgba(255,255,255,0.15)",
            boxShadow: "0 4px 12px rgba(0,0,0,0.3)",
            cursor: "pointer",
            transition: "all 0.2s cubic-bezier(0.16, 1, 0.3, 1)",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.background = "rgba(255, 255, 255, 0.22)";
            e.currentTarget.style.transform = "scale(1.08)";
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.background = "rgba(255, 255, 255, 0.12)";
            e.currentTarget.style.transform = "none";
          }}
          title={`點擊切換 A4 比例卡片尺寸等級 (目前寬度 span: ${scale})`}
        >
          <UIIcon kind="resize" size={12}/>
        </span>
      </div>
    </div>
  );
}

// ─── KanbanPlanCard ───
function KanbanPlanCard({ plan, onDragStart, onClick }) {
  const color = SUBSYSTEM_COLOR[plan.sub] || "var(--accent)";
  return (
    <div
      draggable
      onDragStart={onDragStart}
      onClick={onClick}
      className={`tcard tile hoverable bento-card-${size}`}
      style={{
        padding: 12,
        cursor: "pointer",
        background: "var(--bg-secondary)",
        border: "0.5px solid var(--separator)",
        display: "flex",
        flexDirection: "column",
        gap: 6,
        position: "relative",
      }}
    >
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <SubsystemTag kind={plan.sub} size="sm" withIcon={true} />
        <span className="drag-handle" style={{ opacity: 0.5 }}>
          <UIIcon kind="grip" size={11} />
        </span>
      </div>
      <div style={{
        fontSize: 14,
        fontWeight: 600,
        color: "var(--label-primary)",
        lineHeight: 1.3,
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
      }}>
        {planTitle(plan)}
      </div>
      <div style={{
        fontSize: 11,
        color: "var(--faint)",
        display: "-webkit-box",
        WebkitLineClamp: 2,
        WebkitBoxOrient: "vertical",
        overflow: "hidden",
        lineHeight: 1.3,
      }}>
        {planBodyLines(plan, 2)}
      </div>
    </div>
  );
}

Object.assign(window, { PlansView, PlanCard, KanbanPlanCard });

// ═══════════════════════════════════════════════════════════
//  PEOPLE
// ═══════════════════════════════════════════════════════════
// ─── Person Profile Popup (名片) ───────────────────────────────
function PersonProfilePopup({ person, onClose, onEdit, onDelete }) {
  if (!person) return null;
  const posColor = SUBSYSTEM_COLOR[person.workTypes?.[0]] || "var(--blue)";
  const hasTags = person.workTypes?.length > 0;

  return (
    <CardPreview
      onClose={onClose}
      color={posColor}
      node={<Avatar name={person.name} size={120}/>}
      badges={
        <span style={{
          fontSize: 12, fontWeight: 700, letterSpacing: "0.04em",
          color: posColor,
        }}>{person.position}</span>
      }
      title={person.name}
      subtitle={
        <>
          {person.phone && <div>{person.phone}</div>}
          {person.email && <div>{person.email}</div>}
        </>
      }
      tags={hasTags
        ? person.workTypes.map(w => <SubsystemTag key={w} kind={w} size="sm"/>)
        : [<span key="none" className="pill muted">無指派子系統</span>]}
      meta={[
        { label: "系所", value: person.department || "—" },
        { label: "年級", value: person.grade || "—" },
      ]}
      actions={<>
        <IconBtn danger icon="trash" style={{ marginRight: "auto" }} onClick={() => { onDelete(person); onClose(); }} title="刪除" />
        <IconBtn icon="edit" onClick={() => onEdit(person)} title="編輯" />
      </>}
    />
  );
}

function PeopleView({ people, editPerson, newPerson, onDelete }) {
  const [filter, setFilter] = React.useState("all");
  const [profileId, setProfileId] = React.useState(null);
  const [view, setView] = React.useState("list"); // list | grid (小圖卡)

  const [isMobile, setIsMobile] = React.useState(typeof window !== "undefined" && window.innerWidth <= 768);
  React.useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const totalPeople = people.length;
  const professorCount = people.filter(p => p.position === "教授").length;
  const advisorCount = people.filter(p => p.position === "顧問").length;
  const studentCount = people.filter(p => !["教授", "顧問"].includes(p.position)).length;

  const filtered = filter === "all" ? people : people.filter(p => p.position === filter);
  const profilePerson = people.find(p => p.id === profileId) || null;

  // grid layout configuration
  const gridCols = view === "grid"
    ? (isMobile ? "repeat(2, 1fr)" : "repeat(auto-fill, minmax(180px, 1fr))")
    : "repeat(auto-fill, minmax(280px, 1fr))";

  const gridGap = view === "grid" && isMobile ? 8 : "var(--gap-card)";

  return (
    <div className="people-view" style={{ display: "flex", flexDirection: "column", gap: "var(--gap-zone)" }}>
      <div className="kpi-strip" style={{ display: "flex", gap: "var(--gap-card)" }}>
        <KPI label="STUDENTS" value={studentCount} foot="學生隊員"/>
        <KPI label="ADVISORS" value={advisorCount} foot="專業顧問"/>
        <KPI label="FACULTY"  value={professorCount} foot="指導教授"/>
        <KPI label="TOTAL"    value={totalPeople} foot="團隊總人數" accent/>
      </div>

      {/* Mobile unified single glass pill bar — [role filters] | [view toggle] | [+] */}
      {isMobile && (
        <div className="people-mobile-bar">
          {[
            { id: "all", label: "全" },
            { id: "隊長", label: "長" },
            { id: "副隊長", label: "副" },
            { id: "組長", label: "組" },
            { id: "成員", label: "員" },
            { id: "教授", label: "授" },
          ].map(tag => {
            const active = filter === tag.id;
            return (
              <button key={tag.id} className={active ? "seg-btn--active" : ""} onClick={() => setFilter(tag.id)}
                style={{
                  padding: "0 10px", minWidth: 30, height: 28, borderRadius: 999, border: 0, cursor: "pointer",
                  background: active ? "#fff" : "transparent", flexShrink: 0,
                  color: active ? "var(--ink)" : "var(--faint)",
                  fontSize: 12, fontWeight: active ? 600 : 400,
                  display: "inline-flex", alignItems: "center", justifyContent: "center", transition: "all .15s",
                }}>
                <span>{tag.label}</span>
              </button>
            );
          })}

          {/* Separator */}
          <div style={{ width: 1, alignSelf: "stretch", background: "rgba(120,120,128,0.35)", margin: "4px 3px", flexShrink: 0 }}/>

          {/* View Toggle */}
          <button onClick={() => setView(v => v === "list" ? "grid" : "list")}
            className="seg-btn--active"
            title={view === "list" ? "切換小圖卡" : "切換列表"}
            style={{
              padding: "0 9px", height: 28, borderRadius: 999, border: 0, cursor: "pointer",
              background: "#fff", flexShrink: 0, color: "var(--faint)",
              display: "inline-flex", alignItems: "center", transition: "all .15s",
            }}>
            {view === "list" ? (
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="7" height="7" rx="1" fill="none"/><rect x="14" y="3" width="7" height="7" rx="1" fill="none"/>
                <rect x="3" y="14" width="7" height="7" rx="1" fill="none"/><rect x="14" y="14" width="7" height="7" rx="1" fill="none"/>
                <circle cx="12" cy="12" r="1.2" fill="currentColor"/>
              </svg>
            ) : (
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="4" width="18" height="16" rx="2" fill="none"/>
                <line x1="3" y1="10" x2="21" y2="10"/>
                <line x1="3" y1="16" x2="21" y2="16"/>
              </svg>
            )}
          </button>

          {/* Add Button */}
          <button onClick={newPerson} title="新增成員"
            style={{
              padding: "0 10px", height: 28, borderRadius: 999, border: 0, cursor: "pointer",
              background: "transparent", color: "var(--ink)", flexShrink: 0,
              display: "inline-flex", alignItems: "center",
            }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--faint)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 5v14M5 12h14"/>
            </svg>
          </button>
        </div>
      )}

      {!isMobile && (
        <SectionHead title="成員·Members"
          action={
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <SegmentedFilter className="role-filter" value={filter} onChange={setFilter} options={[
                { id: "all",   label: "全部", shortLabel: "全", uiIcon: "filter" },
                { id: "隊長",  label: "隊長", shortLabel: "長", uiIcon: "users" },
                { id: "副隊長", label: "副隊長", shortLabel: "副", uiIcon: "user" },
                { id: "組長",  label: "組長", shortLabel: "組", uiIcon: "wrench" },
                { id: "成員",  label: "成員", shortLabel: "員", uiIcon: "users" },
                { id: "教授",  label: "教授", shortLabel: "授", uiIcon: "book" },
              ]}/>
              <div style={{ width: 0.5, height: 20, background: "var(--rule)" }} />
              <SegmentedFilter className="view-toggle" value={view} onChange={setView} options={[
                { id: "list", label: "堆疊", uiIcon: "layers" },
                { id: "grid", label: "排列", uiIcon: "filter" },
              ]}/>
              <div style={{ width: 0.5, height: 20, background: "var(--rule)" }} />
              <IconBtn icon="plus" onClick={newPerson} title="新增成員" style={{ borderRadius: 999 }} />
            </div>
          }/>
      )}

      <div style={{
        display: "grid",
        gridTemplateColumns: gridCols,
        gap: gridGap,
      }}>
        {filtered.map(p => (
          <PersonCard key={p.id} person={p} compact={view === "grid"}
            onClick={() => setProfileId(p.id)}/>
        ))}
      </div>

      {profilePerson && (
        <PersonProfilePopup
          person={profilePerson}
          onClose={() => setProfileId(null)}
          onEdit={(p) => { setProfileId(null); editPerson(p); }}
          onDelete={(p) => { setProfileId(null); onDelete(p); }}/>
      )}
    </div>
  );
}

function PersonCard({ person, onClick, compact }) {
  if (compact) {
    const posColors = {
      "隊長": "var(--red)",
      "副隊長": "var(--orange)",
      "組長": "var(--purple)",
      "成員": "var(--blue)",
      "教授": "var(--green)",
      "指導教授": "var(--green)",
      "顧問": "var(--indigo)",
    };
    const posColor = posColors[person.position] || "var(--muted)";
    const posBg = posColor + "15";

    return (
      <div onClick={onClick} className="tcard hoverable large" style={{
        padding: "16px 12px", cursor: "pointer",
        position: "relative", display: "flex", flexDirection: "column",
        alignItems: "center", justifyContent: "center", textAlign: "center",
        gap: 10, height: "100%", transition: "all 0.2s ease",
      }}>
        {/* Avatar */}
        <Avatar name={person.name} size={44} dark/>
        
        {/* Name */}
        <div style={{
          fontFamily: "var(--display-family)",
          fontSize: 15, fontWeight: 700, color: "var(--ink)",
          letterSpacing: "-0.01em", lineHeight: 1.2,
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
          width: "100%",
        }}>{person.name}</div>
        
        {/* Position Badge */}
        <span style={{
          fontSize: 9, fontWeight: 700, letterSpacing: "0.04em",
          color: posColor,
          background: posBg,
          padding: "2px 8px", borderRadius: 99, textTransform: "uppercase",
          border: `0.5px solid ${posColor}25`,
        }}>{person.position}</span>

        {/* Dept & Grade */}
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 9.5,
          color: "var(--muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
          width: "100%", marginTop: 2,
        }}>
          {person.department} · {person.grade}
        </div>
      </div>
    );
  }

  return (
    <div onClick={onClick} className="tcard hoverable large" style={{
      padding: "var(--card-pad)", cursor: "pointer",
      position: "relative",
    }}>
      <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
        <Avatar name={person.name} size={52} dark/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: "var(--display-family)",
            fontSize: 18, fontWeight: 700, color: "var(--ink)",
            letterSpacing: "-0.02em", lineHeight: 1.1,
          }}>{person.name}</div>
          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 11,
            color: "var(--faint)", marginTop: 4,
          }}>{person.email}</div>
          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 9,
            color: "var(--muted)", letterSpacing: "0.06em",
            textTransform: "uppercase", marginTop: 8, paddingTop: 8,
            borderTop: "0.5px solid var(--rule)",
          }}>
            {person.position} · {person.department} · {person.grade}
          </div>
          <div style={{ display: "flex", gap: 4, flexWrap: "wrap", marginTop: 10 }}>
            {person.workTypes?.map(w => <SubsystemTag key={w} kind={w}/>)}
            {(!person.workTypes || person.workTypes.length === 0) && (
              <span className="pill muted">無指派</span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
//  手機版：日誌清單／月曆（首頁手機桌面共用 HomeView）
//  一條條的待辦，只靠「到期日」排序：逾期 → 今天 → 7 天內 → 之後 → 未排期
//  （刻意放在這個檔案：舊版快取的 index.html 不會載入新檔）
// ═══════════════════════════════════════════════════════════
function useIsMobile() {
  const [m, setM] = React.useState(() => window.innerWidth <= 768);
  React.useEffect(() => {
    const onResize = () => setM(window.innerWidth <= 768);
    window.addEventListener("resize", onResize, { passive: true });
    return () => window.removeEventListener("resize", onResize);
  }, []);
  return m;
}

const pad2 = (n) => String(n).padStart(2, "0");
const ymd = (d) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
const parseYmd = (s) => { const [y, m, d] = s.split("-").map(Number); return new Date(y, m - 1, d); };
// 到期日距今天幾天（負數＝已逾期）；沒填到期日回傳 null
function daysUntil(due) {
  if (!due) return null;
  const today = new Date(); today.setHours(0, 0, 0, 0);
  return Math.round((parseYmd(due) - today) / 86400000);
}
function taskBucket(t) {
  if (t.state === "done") return "done";
  const d = daysUntil(t.due);
  if (d === null) return "nodate";
  if (d < 0) return "overdue";
  if (d === 0) return "today";
  if (d <= 7) return "week";
  return "later";
}
function dueLabel(t) {
  const d = daysUntil(t.due);
  if (d === null) return "未排期";
  if (d < 0) return `晚 ${-d} 天`;
  if (d === 0) return "今天";
  if (d === 1) return "明天";
  if (d <= 7) return "週" + "日一二三四五六"[parseYmd(t.due).getDay()];
  const dt = parseYmd(t.due);
  return `${dt.getMonth() + 1}/${dt.getDate()}`;
}
const byDue = (a, b) => (a.due || "9999").localeCompare(b.due || "9999");

function TaskRow({ task, onToggle, onOpen }) {
  const done = task.state === "done";
  const overdue = taskBucket(task) === "overdue";
  return (
    <div className={`mt-row${done ? " is-done" : ""}`}>
      <button className="mt-check" role="checkbox" aria-checked={done}
        aria-label={done ? "標記為未完成" : "標記為完成"} onClick={() => onToggle(task)}>
        {done && <UIIcon kind="check" size={13}/>}
      </button>
      <button className="mt-row-main" onClick={() => onOpen(task)}>
        <span className="mt-row-title">{task.title || "（未命名）"}</span>
        <span className="mt-row-meta">
          {task.owner && task.owner !== "—" && <span>{task.owner}</span>}
          <span className={overdue ? "mt-overdue" : ""}>{dueLabel(task)}</span>
        </span>
      </button>
    </div>
  );
}

function TaskGroup({ label, tone, tasks, onToggle, onOpen }) {
  if (!tasks.length) return null;
  return (
    <section>
      <div className={`mt-section${tone ? " mt-" + tone : ""}`}>{label} <span className="mt-count">{tasks.length}</span></div>
      <div className="mt-card">
        {tasks.map(t => <TaskRow key={t.id} task={t} onToggle={onToggle} onOpen={onOpen}/>)}
      </div>
    </section>
  );
}

// ── 任務：清單／月曆 ──
function MobileTasks({ tasks, onToggle, onOpen, onNew, onDelete }) {
  const [view, setView] = React.useState("calendar");
  const [statsShown] = usePullReveal();
  const [owner, setOwner] = React.useState("all");
  const [showDone, setShowDone] = React.useState(false);
  const owners = [...new Set(tasks.map(t => t.owner).filter(o => o && o !== "—"))].sort();
  const mine = owner === "all" ? tasks : tasks.filter(t => t.owner === owner);
  const pick = (b) => mine.filter(t => taskBucket(t) === b).sort(byDue);
  const done = pick("done");
  return (
    <div className="mt-page">
      <HvStatsLine tasks={tasks} shown={statsShown}/>
      <h1 className="mt-title">任務</h1>
      <div className="mt-toolbar">
        <div className="me-segment" role="radiogroup" style={{ flex: 1 }}>
          {[{ id: "calendar", label: "月曆" }, { id: "gantt", label: "排列" }, { id: "list", label: "堆疊" }].map(o => (
            <button key={o.id} role="radio" aria-checked={view === o.id}
              className={`me-segment-btn${view === o.id ? " is-active" : ""}`}
              onClick={() => setView(o.id)}>{o.label}</button>
          ))}
        </div>
        <select className="mt-owner" aria-label="負責人" value={owner} onChange={e => setOwner(e.target.value)}>
          <option value="all">全部的人</option>
          {owners.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      </div>

      {view === "list" ? (
        <>
          <TaskGroup label="逾期" tone="red" tasks={pick("overdue")} onToggle={onToggle} onOpen={onOpen}/>
          <TaskGroup label="今天" tasks={pick("today")} onToggle={onToggle} onOpen={onOpen}/>
          <TaskGroup label="7 天內" tasks={pick("week")} onToggle={onToggle} onOpen={onOpen}/>
          <TaskGroup label="之後" tasks={pick("later")} onToggle={onToggle} onOpen={onOpen}/>
          <TaskGroup label="未排期" tasks={pick("nodate")} onToggle={onToggle} onOpen={onOpen}/>
          {mine.length === done.length && <div className="mt-empty">沒有待辦。按下方的 ＋ 新增一件。</div>}
          {done.length > 0 && (
            <>
              <button className="mt-done-toggle" aria-expanded={showDone} onClick={() => setShowDone(v => !v)}>
                已完成 {done.length} 件 <UIIcon kind={showDone ? "chevron-down" : "chevron-right"} size={14}/>
              </button>
              {showDone && (
                <div className="mt-card">
                  {done.map(t => <TaskRow key={t.id} task={t} onToggle={onToggle} onOpen={onOpen}/>)}
                </div>
              )}
            </>
          )}
        </>
      ) : view === "gantt" ? (
        <GanttChart tasks={mine} onTaskClick={onOpen} onDelete={onDelete}/>
      ) : (
        <MobileCalendar tasks={mine} onToggle={onToggle} onOpen={onOpen} onNew={onNew}/>
      )}
    </div>
  );
}

// 手機月曆：點陣大月曆＋選到那天的清單
function MobileCalendar({ tasks, onToggle, onOpen, onNew }) {
  const [sel, setSel] = React.useState(() => ymd(new Date()));
  const selTasks = tasks.filter(t => t.due === sel).sort((a, b) => (a.state === "done") - (b.state === "done"));
  const selDate = sel ? parseYmd(sel) : null;
  return (
    <>
      <div className="mt-card" style={{ padding: "12px 10px" }}>
        <HvCalendar tasks={tasks} weeks={5} variant="full" sel={sel} onSel={(d) => setSel(d || sel)} onOpen={onOpen} onNew={onNew}/>
      </div>
      {selDate && (
        <>
          <div className="mt-section">{selDate.getMonth() + 1}月{selDate.getDate()}日 <span className="mt-count">{selTasks.length}</span></div>
          {selTasks.length ? (
            <div className="mt-card">
              {selTasks.map(t => <TaskRow key={t.id} task={t} onToggle={onToggle} onOpen={onOpen}/>)}
            </div>
          ) : <div className="mt-empty">這天沒有到期的任務。<button className="hv-text-btn" style={{ display: "inline" }} onClick={() => onNew?.({ due: sel })}>新增一件</button></div>}
        </>
      )}
    </>
  );
}

// ═══════════════════════════════════════════════════════════
//  HOME 與 LOG 的新元件
//   HvCalendar   點陣月曆（從這週起排連續幾週，參考「高科校園」）
//   HvMatrix     本週待辦四象限（重要 × 緊急），點可拖、可點開編輯
//   HvWeekList   本週重點清單
//   HvCarPreview 車體預覽（tools/envelope.html?embed）
//   HomeView     首頁：左上車體、右上月曆、左下清單、右下象限
//   usePullReveal 捲到頂再往上拉才出現的東西（LOG 的統計）
// 共用 Dashboard.jsx 的 ymd / parseYmd / daysUntil / dueLabel / taskBucket / byDue（全域）

const HV_WD = ["一", "二", "三", "四", "五", "六", "日"];
const hvMonday = (d) => { const x = new Date(d); x.setHours(0, 0, 0, 0); x.setDate(x.getDate() - ((x.getDay() + 6) % 7)); return x; };
const hvAdd = (d, n) => { const x = new Date(d); x.setDate(x.getDate() + n); return x; };
const hvMD = (s) => { const d = parseYmd(s); return `${d.getMonth() + 1}/${d.getDate()}`; };
const hvOpen = (t) => t.state !== "done";

// 本週待辦：沒完成，而且「已逾期／7 天內到期／還沒排日期／本週焦點」
function hvThisWeek(tasks) {
  return tasks.filter(t => {
    if (!hvOpen(t)) return false;
    const d = daysUntil(t.due);
    return d === null || d <= 7 || t.state === "focus";
  });
}

// ─── 點陣月曆 ─────────────────────────────────────────────
// variant="dot"：首頁小月曆，一天一個點；variant="full"：LOG 大月曆，格子裡寫事項
function HvCalendar({ tasks, weeks = 4, variant = "dot", sel, onSel, onOpen, onNew }) {
  const today = ymd(new Date());
  const [offset, setOffset] = React.useState(0);            // 以週為單位往前後翻
  const start = hvAdd(hvMonday(new Date()), offset * 7);
  const days = Array.from({ length: weeks * 7 }, (_, i) => hvAdd(start, i));
  const byDay = {};
  tasks.forEach(t => { if (t.due) (byDay[t.due] = byDay[t.due] || []).push(t); });
  const end = days[days.length - 1];
  const thisWeek0 = ymd(hvMonday(new Date())), thisWeek1 = ymd(hvAdd(hvMonday(new Date()), 6));
  const full = variant === "full";
  return (
    <div className={`hv-cal hv-cal--${variant}`}>
      <div className="hv-cal-nav">
        <span className="hv-mono">{start.getMonth() + 1}/{start.getDate()} – {end.getMonth() + 1}/{end.getDate()}</span>
        <span className="hv-cal-navbtns">
          {offset !== 0 && <button className="hv-text-btn" onClick={() => setOffset(0)}>今天</button>}
          <button className="hv-icon-btn" aria-label="往前" onClick={() => setOffset(o => o - weeks)}>
            <span style={{ display: "inline-flex", transform: "rotate(180deg)" }}><UIIcon kind="chevron-right" size={14}/></span>
          </button>
          <button className="hv-icon-btn" aria-label="往後" onClick={() => setOffset(o => o + weeks)}>
            <UIIcon kind="chevron-right" size={14}/>
          </button>
        </span>
      </div>
      <div className="hv-cal-grid">
        {HV_WD.map(d => <div key={d} className="hv-cal-wd">{d}</div>)}
        {days.map(d => {
          const key = ymd(d);
          const list = (byDay[key] || []).slice().sort((a, b) => hvOpen(b) - hvOpen(a));
          const open = list.filter(hvOpen).length;
          const cls = ["hv-day",
            key < today ? "is-past" : "",
            key === today ? "is-today" : "",
            key === sel ? "is-sel" : "",
            key >= thisWeek0 && key <= thisWeek1 ? "is-wk" : "",
            list.length ? (open ? (key < today ? "has-late" : "has-open") : "has-done") : "",
          ].filter(Boolean).join(" ");
          const size = list.length >= 3 ? 12 : list.length === 2 ? 10 : 8;
          const label = d.getDate() === 1 ? `${d.getMonth() + 1}/1` : d.getDate();
          return (
            <div key={key} className={cls} role="button" tabIndex={0}
              aria-label={`${d.getMonth() + 1}月${d.getDate()}日${list.length ? "，" + list.map(t => t.title).join("、") : ""}`}
              onClick={() => onSel?.(sel === key ? null : key)}
              onDoubleClick={() => full && onNew?.({ due: key })}
              onKeyDown={e => { if (e.key === "Enter") onSel?.(sel === key ? null : key); }}>
              {full ? (
                <>
                  <span className="hv-day-num">{label}</span>
                  <div className="hv-day-items">
                    {list.slice(0, 3).map(t => (
                      <button key={t.id} className={"hv-day-item" + (hvOpen(t) ? "" : " is-done")}
                        onClick={e => { e.stopPropagation(); onOpen?.(t); }}>
                        <i/>{t.title || "（未命名）"}
                      </button>
                    ))}
                    {list.length > 3 && <span className="hv-day-more">+{list.length - 3}</span>}
                  </div>
                </>
              ) : (
                <>
                  {list.length ? <i className="hv-dot" style={{ width: size, height: size }}/> : <i className="hv-dot hv-dot--empty"/>}
                  <span className="hv-day-num">{label}</span>
                </>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// 月曆下面的清單：選了某天就列那天，沒選就列接下來的事
function HvAgenda({ tasks, sel, onOpen, limit = 6 }) {
  const today = ymd(new Date());
  const list = sel
    ? tasks.filter(t => t.due === sel)
    : tasks.filter(t => hvOpen(t) && t.due && t.due >= today).sort(byDue).slice(0, limit);
  return (
    <div className="hv-agenda">
      <div className="hv-eyebrow">{sel ? hvMD(sel) : "接下來"}</div>
      {list.length === 0 && <div className="hv-empty">{sel ? "這天沒有事項" : "接下來沒有排定的事"}</div>}
      {list.map((t, i) => (
        <button key={t.id} className={"hv-agenda-row" + (hvOpen(t) ? "" : " is-done")} onClick={() => onOpen(t)}>
          <span className="hv-mono hv-agenda-date">{!sel && (i === 0 || list[i - 1].due !== t.due) ? hvMD(t.due) : ""}</span>
          <span className="hv-agenda-title">{t.title || "（未命名）"}</span>
          {t.owner && t.owner !== "—" && <span className="hv-agenda-owner">{t.owner}</span>}
        </button>
      ))}
    </div>
  );
}

// 短期目標：沒完成，4 週內到期、已逾期或還沒排日期（比本週清單寬）
function hvShortTerm(tasks) {
  return tasks.filter(t => {
    if (!hvOpen(t)) return false;
    const d = daysUntil(t.due);
    return d === null || d <= 28 || t.state === "focus";
  });
}

// ─── 四象限 ───────────────────────────────────────────────
// 位置：橫軸 urg（右＝緊急）、縱軸 imp（上＝重要），0–1。
// 沒拖過的事項用到期日和優先度推一個位置；拖過就記在任務上（imp / urg）。
function hvHash(s) { let h = 0; for (const c of String(s)) h = (h * 31 + c.charCodeAt(0)) | 0; return h; }
function hvPos(t) {
  const j = (k) => ((hvHash(t.id + k) % 1000) / 1000 - 0.5) * 0.12;  // 小小錯開，避免疊在一起
  let urg = t.urg, imp = t.imp;
  if (urg == null) {
    const d = daysUntil(t.due);
    // 沒到期日：用甘特圖的週次推（甘特圖把 W5 當本週），剩越少週越緊急
    const left = (+t.start || 0) + (+t.span || 0) - 5;
    urg = d !== null ? (d < 0 ? 0.92 : d <= 1 ? 0.84 : d <= 3 ? 0.72 : d <= 7 ? 0.6 : 0.3)
        : left <= 0 ? 0.56 : Math.max(0.08, 0.46 - left * 0.05);
    urg += j("u");
  }
  if (imp == null) {
    imp = t.priority === "HIGH" ? 0.82 : t.priority === "MID" ? 0.6 : t.priority === "LOW" ? 0.22 : t.state === "focus" ? 0.75 : 0.4;
    imp += j("i");
  }
  const c = (v) => Math.min(0.96, Math.max(0.04, v));
  return { urg: c(urg), imp: c(imp) };
}

function HvMatrix({ tasks, onOpen, onNew, onMove }) {
  const ref = React.useRef(null);
  const [drag, setDrag] = React.useState(null);   // { id, urg, imp, moved }
  const items = hvShortTerm(tasks);
  // 擺位置；太靠近的往上下推開，標籤才不會疊在一起
  const pos = React.useMemo(() => {
    const ps = items.map(t => ({ id: t.id, ...hvPos(t) })).sort((a, b) => b.imp - a.imp);
    for (let k = 0; k < 6; k++) {
      for (let i = 0; i < ps.length; i++) for (let j = i + 1; j < ps.length; j++) {
        const a = ps[i], b = ps[j];
        if (Math.abs(a.urg - b.urg) < 0.3 && Math.abs(a.imp - b.imp) < 0.075) {
          const push = (0.075 - Math.abs(a.imp - b.imp)) / 2 + 0.002;
          a.imp = Math.min(0.97, a.imp + push); b.imp = Math.max(0.03, b.imp - push);
        }
      }
    }
    return Object.fromEntries(ps.map(p => [p.id, p]));
  }, [items.map(t => `${t.id}:${t.imp}:${t.urg}:${t.due}:${t.priority}`).join("|")]);
  const toPos = (e) => {
    const r = ref.current.getBoundingClientRect();
    const c = (v) => Math.min(0.97, Math.max(0.03, v));
    return { urg: c((e.clientX - r.left) / r.width), imp: c(1 - (e.clientY - r.top) / r.height) };
  };
  const down = (e, t) => {
    e.stopPropagation();
    e.currentTarget.setPointerCapture(e.pointerId);
    setDrag({ id: t.id, ...pos[t.id], x0: e.clientX, y0: e.clientY, moved: false });
  };
  const move = (e) => {
    if (!drag) return;
    const moved = drag.moved || Math.hypot(e.clientX - drag.x0, e.clientY - drag.y0) > 4;
    setDrag({ ...drag, ...(moved ? toPos(e) : {}), moved });
  };
  const up = (e, t) => {
    if (!drag) return;
    if (drag.moved) onMove(t, { urg: +drag.urg.toFixed(3), imp: +drag.imp.toFixed(3) });
    else onOpen(t);
    setDrag(null);
  };
  return (
    <div className="hv-matrix-wrap">
      <div className="hv-matrix" ref={ref}
        onClick={e => { if (e.target === ref.current || e.target.classList.contains("hv-q")) onNew(toPos(e)); }}>
        <div className="hv-axis hv-axis--x"/><div className="hv-axis hv-axis--y"/>
        <span className="hv-q hv-q--tl">重要・不急</span>
        <span className="hv-q hv-q--tr">重要・緊急</span>
        <span className="hv-q hv-q--bl">不重要・不急</span>
        <span className="hv-q hv-q--br">緊急・不重要</span>
        {items.map(t => {
          const p = drag && drag.id === t.id ? drag : pos[t.id];
          const late = (daysUntil(t.due) ?? 1) < 0;
          return (
            <button key={t.id}
              className={"hv-pin" + (drag && drag.id === t.id ? " is-drag" : "") + (late ? " is-late" : "") + (p.urg > 0.62 ? " is-left" : "")}
              style={{ left: `${p.urg * 100}%`, top: `${(1 - p.imp) * 100}%` }}
              onPointerDown={e => down(e, t)} onPointerMove={move} onPointerUp={e => up(e, t)}
              onPointerCancel={() => setDrag(null)}
              title={`${t.title}${t.due ? " · " + dueLabel(t) : ""}（拖曳調整位置，點一下編輯）`}>
              <i/><span>{t.title || "（未命名）"}</span>
            </button>
          );
        })}
        {items.length === 0 && <div className="hv-empty hv-matrix-empty">沒有短期目標。點空白處新增。</div>}
      </div>
    </div>
  );
}

// ─── 本週重點清單 ─────────────────────────────────────────
function HvWeekList({ tasks, onToggle, onOpen }) {
  const order = { overdue: 0, today: 1, week: 2, nodate: 4, later: 3 };
  const list = hvThisWeek(tasks).slice().sort((a, b) =>
    (order[taskBucket(a)] - order[taskBucket(b)]) || byDue(a, b));
  const weekAgo = Date.now() - 7 * 86400000;
  const doneWeek = tasks.filter(t => t.state === "done" && t.doneAt && t.doneAt >= weekAgo);
  return (
    <div className="hv-list">
      {list.length === 0 && <div className="hv-empty">本週沒有待辦</div>}
      {list.map(t => {
        const b = taskBucket(t);
        return (
          <div key={t.id} className="hv-list-row">
            <button className="hv-check" role="checkbox" aria-checked={false} aria-label="標記為完成" onClick={() => onToggle(t)}/>
            <button className="hv-list-main" onClick={() => onOpen(t)}>
              <span className="hv-list-title">{t.title || "（未命名）"}</span>
              {t.owner && t.owner !== "—" && <span className="hv-list-owner">{t.owner}</span>}
            </button>
            <span className={"hv-mono hv-list-due" + (b === "overdue" ? " is-late" : b === "today" ? " is-today" : "")}>{dueLabel(t)}</span>
          </div>
        );
      })}
      {doneWeek.map(t => (
        <div key={t.id} className="hv-list-row is-done">
          <button className="hv-check is-on" role="checkbox" aria-checked={true} aria-label="標記為未完成" onClick={() => onToggle(t)}>
            <UIIcon kind="check" size={11}/>
          </button>
          <button className="hv-list-main" onClick={() => onOpen(t)}>
            <span className="hv-list-title">{t.title}</span>
          </button>
          <span className="hv-mono hv-list-due">完成</span>
        </div>
      ))}
    </div>
  );
}

// ─── 車體預覽 ─────────────────────────────────────────────
function HvCarPreview({ onOpenDesign }) {
  const post = (win) => {
    const theme = document.documentElement.getAttribute("data-appearance")
      || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
    win?.postMessage({ type: "appearance", value: theme }, location.origin);
  };
  return (
    <div className="hv-car">
      <iframe data-frame-tool title="車體預覽" src="tools/envelope.html?embed" loading="lazy"
        onLoad={e => post(e.target.contentWindow)}/>
      <button className="hv-car-open" onClick={onOpenDesign}>開啟 DESIGN <UIIcon kind="arrow" size={12}/></button>
    </div>
  );
}

// ─── HOME ────────────────────────────────────────────────
function HomeView({ tasks, onToggle, onOpen, onNew, onMove, onNavigate }) {
  const [sel, setSel] = React.useState(null);
  const items = hvThisWeek(tasks);
  const now = new Date();
  return (
    <div className="hv-home">
      <section className="tcard large hv-card hv-area-car">
        <header className="hv-head">
          <span className="hv-eyebrow">DESIGN</span>
          <span className="hv-mono">車架・整車配置</span>
        </header>
        <HvCarPreview onOpenDesign={() => onNavigate("frame")}/>
      </section>

      <section className="tcard large hv-card hv-area-cal">
        <header className="hv-head">
          <span className="hv-eyebrow">CALENDAR</span>
          <span className="hv-mono">{now.getMonth() + 1}月{now.getDate()}日 週{"日一二三四五六"[now.getDay()]}</span>
        </header>
        <HvCalendar tasks={tasks} weeks={4} sel={sel} onSel={setSel}/>
        <HvAgenda tasks={tasks} sel={sel} onOpen={onOpen} limit={5}/>
      </section>

      <section className="hv-card hv-bare hv-area-list">
        <header className="hv-head">
          <span className="hv-eyebrow">本週重點</span>
          <span className="hv-mono"><b className="hv-big">{items.length}</b> 件待辦</span>
        </header>
        <HvWeekList tasks={tasks} onToggle={onToggle} onOpen={onOpen}/>
      </section>

      <section className="hv-card hv-bare hv-area-matrix">
        <header className="hv-head">
          <span className="hv-eyebrow">短期目標</span>
          <button className="hv-add" aria-label="新增事項" title="新增事項" onClick={() => onNew({})}>
            <UIIcon kind="plus" size={16}/>
          </button>
        </header>
        <HvMatrix tasks={tasks} onOpen={onOpen} onNew={onNew} onMove={onMove}/>
      </section>
    </div>
  );
}

// ─── 捲到頂再往上拉才出現 ─────────────────────────────────
// 滑鼠：在頁頂繼續往上捲；觸控：在頁頂往下拖。往下捲離開頂端就收起。
function usePullReveal(threshold = 90) {
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    let acc = 0, y0 = null, reset;
    const atTop = () => window.scrollY <= 0;
    const bump = (d) => {
      acc += d; clearTimeout(reset); reset = setTimeout(() => { acc = 0; }, 400);
      if (acc > threshold) { setShown(true); acc = 0; }
    };
    const onWheel = (e) => { if (atTop() && e.deltaY < 0) bump(-e.deltaY); };
    const onTouchStart = (e) => { y0 = atTop() ? e.touches[0].clientY : null; };
    const onTouchMove = (e) => { if (y0 != null) { const d = e.touches[0].clientY - y0; if (d > threshold) { setShown(true); y0 = null; } } };
    const onScroll = () => { if (window.scrollY > 60) setShown(false); };
    window.addEventListener("wheel", onWheel, { passive: true });
    window.addEventListener("touchstart", onTouchStart, { passive: true });
    window.addEventListener("touchmove", onTouchMove, { passive: true });
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => {
      clearTimeout(reset);
      window.removeEventListener("wheel", onWheel);
      window.removeEventListener("touchstart", onTouchStart);
      window.removeEventListener("touchmove", onTouchMove);
      window.removeEventListener("scroll", onScroll);
    };
  }, [threshold]);
  return [shown, setShown];
}

// LOG 的精簡統計：一列小字
function HvStatsLine({ tasks, shown }) {
  const open = tasks.filter(hvOpen);
  const late = open.filter(t => taskBucket(t) === "overdue").length;
  const week = open.filter(t => ["today", "week"].includes(taskBucket(t))).length;
  const avg = tasks.length ? Math.round(tasks.reduce((a, t) => a + (+t.progress || 0), 0) / tasks.length) : 0;
  const cells = [["TOTAL", tasks.length], ["ACTIVE", open.length], ["7 DAYS", week], ["OVERDUE", late], ["AVG", avg + "%"]];
  return (
    <div className={"hv-stats" + (shown ? " is-shown" : "")} aria-hidden={!shown}>
      {cells.map(([k, v]) => (
        <span key={k} className={k === "OVERDUE" && late ? "is-late" : ""}><b>{v}</b>{k}</span>
      ))}
    </div>
  );
}

Object.assign(window, { Dashboard, BentoCard, PersonCard });
