// Portfolio screen — Sprint B Phase 2 · executive-first project overview.
// Also registers a tiny placeholder for `/brief/:id` so clicks don't 404
// — the real Brief screen lands in Sprint B Phase 3.
// Mobile-first: card view default below 1024px, list view above.
// View toggle: List · Card · Gantt (reuses window.Gantt — no new timeline engine).
// Sort: starred → due_date → priority → progress (via window.byPortfolio from B-1).
// Click any project → /brief/:id (Project Brief screen lands in B-3).
(function () {
  window.SCREENS = window.SCREENS || {};
  const { useState, useEffect } = React;
  const IC = window.IC, D = window.DATA;

  // ── Helpers ─────────────────────────────────────────────────
  const sm = D.statusMeta, pm = D.priorityMeta;
  const sortByDateDesc = window.sortByDateDesc || ((a) => a.slice());

  function isMobile() {
    try { return window.matchMedia && !window.matchMedia("(min-width: 1024px)").matches; }
    catch (e) { return true; }
  }

  function latestUpdateOf(p) {
    const ups = (D.updates || []).filter((u) => u.projectId === p.id || u.project === p.name);
    return sortByDateDesc(ups)[0] || null;
  }
  function nextStepOf(p) {
    // D.nextSteps may not exist on this branch (Sprint A asset) — handle gracefully
    const steps = (D.nextSteps || []).filter((s) => s.projectId === p.id && (s.status === "pending" || s.status === "in_progress"));
    return steps[0] || null;   // already sorted by byNextStep at the data layer
  }
  function dueLabel(p) {
    if (!p.end) return "ไม่กำหนด";
    return window.isoToBE ? window.isoToBE(p.end) : p.end;
  }
  function dueTone(p) {
    if (!p.end) return "neutral";
    const today = window.todayISO ? window.todayISO() : new Date().toISOString().slice(0,10);
    if (p.end < today) return "danger";
    const ms = new Date(p.end + "T00:00:00") - new Date(today + "T00:00:00");
    const days = ms / 86400000;
    if (days <= 14) return "warn";
    return "ok";
  }

  // ── Reusable star button (works desktop + mobile; tap target ≥ 40px) ──
  function StarButton({ p, canEdit }) {
    const [busy, setBusy] = useState(false);
    const onClick = async (e) => {
      e.preventDefault(); e.stopPropagation();
      if (busy || !canEdit) return;
      setBusy(true);
      try { await window.DB.toggleProjectStar(p.id); }
      finally { setBusy(false); }
    };
    if (!canEdit) {
      // Read-only: show filled star only when starred; nothing when not
      return p.starred
        ? <span title="ปักหมุด" style={{ color: "var(--warn)", fontSize: 20, lineHeight: 1, padding: 4, display: "inline-block" }}>★</span>
        : <span style={{ width: 28, display: "inline-block" }} />;
    }
    return (
      <button type="button" className="icon-btn" onClick={onClick} disabled={busy}
        title={p.starred ? "ยกเลิกการปักหมุด" : "ปักหมุดโครงการ"}
        style={{ width: 40, height: 40, color: p.starred ? "var(--warn)" : "var(--faint)", fontSize: 20, padding: 0 }}>
        <span style={{ fontSize: 20, lineHeight: 1 }}>{p.starred ? "★" : "☆"}</span>
      </button>
    );
  }

  // ── Card view (default on mobile, optional on desktop) ─────────────────
  function CardView({ projects, canEdit }) {
    if (projects.length === 0) {
      return <window.EmptyState icon="folder" title="ยังไม่มีโครงการ" sub="เริ่มต้นจากการสร้างโครงการแรก แล้วระบบจะสร้าง Timeline และโมดูลให้อัตโนมัติ" ctaLabel={canEdit ? "สร้างโครงการแรก" : undefined} onCta={canEdit ? () => window.navigate("projects") : undefined} />;
    }
    return (
      <div style={{ display: "grid", gap: 12, gridTemplateColumns: "repeat(auto-fill, minmax(min(100%, 320px), 1fr))" }}>
        {projects.map((p) => {
          const upd = latestUpdateOf(p);
          const ns  = nextStepOf(p);
          const dTone = dueTone(p);
          const dLabel = dueLabel(p);
          const open = () => window.navigate("brief/" + p.id);
          return (
            <div key={p.id} className="rail-card" style={{ padding: 16, cursor: "pointer", display: "flex", flexDirection: "column", gap: 12, borderLeft: p.starred ? "3px solid var(--warn)" : "3px solid transparent" }}
                 onClick={open} role="button" tabIndex={0} onKeyDown={(e) => { if (e.key === "Enter") open(); }}>
              {/* head: star + code + name + status + health */}
              <div style={{ display: "flex", alignItems: "flex-start", gap: 8, minWidth: 0 }}>
                <div style={{ flex: "none" }} onClick={(e) => e.stopPropagation()}>
                  <StarButton p={p} canEdit={canEdit} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="eyebrow" style={{ marginBottom: 2 }}>{p.code} · {(sm[p.status] || {}).th || p.status}</div>
                  <div style={{ fontSize: 16, fontWeight: 600, lineHeight: 1.3, wordBreak: "break-word" }}>{p.name}</div>
                </div>
                {(() => { const h = window.computeHealthScore ? window.computeHealthScore(p, (D.detail && D.detail[p.id]) || {}) : null;
                  return h ? <span className={"health-badge tone-" + h.tone} style={{ flex: "none" }} title="Health Score"><span className="num">{h.score}</span></span> : null;
                })()}
              </div>

              {/* progress */}
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--muted)", marginBottom: 4 }}>
                  <span>Progress</span><b className="tnum" style={{ color: "var(--ink)" }}>{p.progress || 0}%</b>
                </div>
                <div className="prog-bar"><i style={{ width: (p.progress || 0) + "%" }} /></div>
              </div>

              {/* 5 fields */}
              <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", columnGap: 10, rowGap: 6, fontSize: 13 }}>
                <span style={{ color: "var(--muted)" }}>{IC.trend} อัปเดต</span>
                <span style={{ minWidth: 0, color: upd ? "var(--ink2)" : "var(--faint)", wordBreak: "break-word" }}>
                  {upd ? (<><b style={{ color: "var(--ink)" }}>{upd.title}</b><br /><span style={{ fontSize: 11.5, color: "var(--muted)" }}>{upd.date}</span></>) : "ยังไม่มีอัปเดต"}
                </span>

                <span style={{ color: "var(--muted)" }}>{IC.check} Next</span>
                <span style={{ minWidth: 0, color: ns ? "var(--ink2)" : "var(--faint)", wordBreak: "break-word" }}>
                  {ns ? (<><b style={{ color: "var(--ink)" }}>{ns.title}</b><br /><span style={{ fontSize: 11.5, color: "var(--muted)" }}>{ns.dueDate ? "ครบกำหนด " + (window.isoToBE ? window.isoToBE(ns.dueDate) : ns.dueDate) : "ไม่กำหนด"}</span></>) : "ยังไม่มี Next Step"}
                </span>

                <span style={{ color: "var(--muted)" }}>{IC.cal} ส่งมอบ</span>
                <span className={"pill " + dTone} style={{ alignSelf: "center", justifySelf: "start", fontSize: 12 }}><i />{dLabel}</span>

                <span style={{ color: "var(--muted)" }}>{IC.user} เจ้าของ</span>
                <span style={{ display: "flex", alignItems: "center", gap: 7, minWidth: 0 }}>
                  {p.owner
                    ? <><span className="avatar sm" style={{ background: "var(--raised2)", color: "var(--muted)", flex: "none" }}>{p.ownerInit || (p.owner || "?").slice(0,2)}</span><span style={{ wordBreak: "break-word" }}>{p.owner}</span></>
                    : <span style={{ color: "var(--faint)" }}>ไม่ระบุ</span>}
                </span>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  // ── List view (table-like, dense; default on desktop) ─────────────────
  function ListView({ projects, canEdit }) {
    if (projects.length === 0) {
      return <window.EmptyState icon="folder" title="ยังไม่มีโครงการ" sub="เริ่มต้นจากการสร้างโครงการแรก" ctaLabel={canEdit ? "สร้างโครงการแรก" : undefined} onCta={canEdit ? () => window.navigate("projects") : undefined} />;
    }
    const headerCell = { fontSize: 11.5, fontWeight: 700, color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".04em", padding: "10px 12px", textAlign: "left" };
    const cell = { padding: "12px", fontSize: 13.5, verticalAlign: "top", borderTop: "1px solid var(--line-soft)" };
    return (
      <div className="rail-card" style={{ padding: 0, overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 880 }}>
          <thead>
            <tr style={{ background: "var(--raised)" }}>
              <th style={{ ...headerCell, width: 44 }}></th>
              <th style={headerCell}>โครงการ</th>
              <th style={{ ...headerCell, width: 140 }}>Progress</th>
              <th style={headerCell}>อัปเดตล่าสุด</th>
              <th style={headerCell}>Next Step</th>
              <th style={{ ...headerCell, width: 140 }}>ส่งมอบ</th>
              <th style={{ ...headerCell, width: 130 }}>เจ้าของ</th>
            </tr>
          </thead>
          <tbody>
            {projects.map((p) => {
              const upd = latestUpdateOf(p);
              const ns  = nextStepOf(p);
              const dTone = dueTone(p);
              const open = () => window.navigate("brief/" + p.id);
              return (
                <tr key={p.id} onClick={open} style={{ cursor: "pointer", background: p.starred ? "var(--warn-tint, transparent)" : "transparent" }}>
                  <td style={cell} onClick={(e) => e.stopPropagation()}>
                    <StarButton p={p} canEdit={canEdit} />
                  </td>
                  <td style={cell}>
                    <div style={{ fontSize: 11.5, color: "var(--muted)" }}>{p.code}</div>
                    <div style={{ fontWeight: 600, wordBreak: "break-word" }}>{p.name}</div>
                    <div style={{ display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap", marginTop: 4 }}>
                      <span className={"pill " + ((sm[p.status]||{}).tone || "neutral")} style={{ fontSize: 11 }}><i />{(sm[p.status]||{}).th || p.status}</span>
                      {(() => { const h = window.computeHealthScore ? window.computeHealthScore(p, (D.detail && D.detail[p.id]) || {}) : null;
                        return h ? <span className={"health-badge tone-" + h.tone}><span className="num">{h.score}</span> {h.label}</span> : null;
                      })()}
                    </div>
                  </td>
                  <td style={cell}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <div className="prog-bar" style={{ flex: 1, minWidth: 60 }}><i style={{ width: (p.progress || 0) + "%" }} /></div>
                      <b className="tnum" style={{ fontSize: 13, color: "var(--ink)" }}>{p.progress || 0}%</b>
                    </div>
                  </td>
                  <td style={cell}>
                    {upd ? (<><b>{upd.title}</b><div style={{ fontSize: 11.5, color: "var(--muted)" }}>{upd.date}</div></>) : <span style={{ color: "var(--faint)" }}>ยังไม่มีอัปเดต</span>}
                  </td>
                  <td style={cell}>
                    {ns ? (<><b>{ns.title}</b><div style={{ fontSize: 11.5, color: "var(--muted)" }}>{ns.dueDate ? "ครบกำหนด " + (window.isoToBE ? window.isoToBE(ns.dueDate) : ns.dueDate) : "ไม่กำหนด"}</div></>) : <span style={{ color: "var(--faint)" }}>ยังไม่มี Next Step</span>}
                  </td>
                  <td style={cell}>
                    <span className={"pill " + dTone} style={{ fontSize: 12 }}><i />{dueLabel(p)}</span>
                  </td>
                  <td style={cell}>
                    {p.owner
                      ? <div style={{ display: "flex", alignItems: "center", gap: 7 }}><span className="avatar sm" style={{ background: "var(--raised2)", color: "var(--muted)" }}>{p.ownerInit || (p.owner || "?").slice(0,2)}</span><span style={{ wordBreak: "break-word" }}>{p.owner}</span></div>
                      : <span style={{ color: "var(--faint)" }}>ไม่ระบุ</span>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }

  // ── Gantt view — reuses window.Gantt with synthetic project-as-phase entries ─
  // Each project becomes a "phase". onPhaseClick navigates to Brief.
  function statusToPhaseStatus(s) {
    if (s === "in_progress") return "active";
    if (s === "completed") return "done";
    if (s === "at_risk" || s === "blocked") return "at_risk";
    return "todo";
  }
  function GanttView({ projects }) {
    if (projects.length === 0) {
      return <window.EmptyState icon="gantt" title="ยังไม่มี Timeline" sub="ต้องมีโครงการก่อน — สร้างโครงการเพื่อให้ Timeline ปรากฏ" />;
    }
    // Compute global window: earliest start → latest end
    let minStart = "", maxEnd = "";
    for (const p of projects) {
      if (p.start && (!minStart || p.start < minStart)) minStart = p.start;
      if (p.end && (!maxEnd || p.end > maxEnd)) maxEnd = p.end;
    }
    if (!minStart) minStart = window.todayISO ? window.todayISO() : new Date().toISOString().slice(0,10);
    if (!maxEnd) maxEnd = minStart;
    const startISO = minStart;
    const totalDays = Math.max(60, window.isoToDay ? window.isoToDay(maxEnd, startISO) : 365);
    const today = window.isoToDay ? Math.max(0, Math.min(totalDays, window.isoToDay(window.todayISO ? window.todayISO() : new Date().toISOString().slice(0,10), startISO))) : 0;
    const phases = projects.map((p) => {
      const s = window.isoToDay ? Math.max(0, window.isoToDay(p.start || startISO, startISO)) : 0;
      const e = window.isoToDay ? Math.max(s, window.isoToDay(p.end || maxEnd, startISO)) : totalDays;
      return {
        id: p.id, name: p.name, en: p.code, owner: p.owner || "", ownerInit: p.ownerInit || (p.owner || "?").slice(0,2),
        status: statusToPhaseStatus(p.status), progress: p.progress || 0,
        s, e, startISO: p.start, endISO: p.end, tasks: [], _project: p,
      };
    });
    return (
      <div className="gantt-wrap">
        <div className="gantt-tools">
          <span style={{ fontSize: 12.5, color: "var(--muted)" }}>คลิกชื่อโครงการเพื่อเปิดบรีฟ</span>
          <div className="legend">
            <span className="lg"><span className="barx" style={{ background: "var(--accent)" }} />กำลังทำ</span>
            <span className="lg"><span className="barx" style={{ background: "var(--ok)" }} />เสร็จ</span>
            <span className="lg"><span className="barx" style={{ background: "#B9B0A0" }} />ยังไม่เริ่ม</span>
          </div>
        </div>
        <window.Gantt phases={phases} mode="exec" startISO={startISO} todayDay={today} totalDays={totalDays}
                      onPhaseClick={(ph) => window.navigate("brief/" + ph.id)} />
      </div>
    );
  }

  // ── Placeholder: /brief/:id will be implemented in B-3 ──────
  // Until then, navigating from a Portfolio click shows this stub so the
  // route is recognised + the user knows it's pending.
  window.SCREENS.brief = function BriefPlaceholder({ route }) {
    const p = (D.projects || []).find((x) => x.id === route.id);
    if (!p) {
      return <div className="page wide"><div className="empty">ไม่พบโครงการ</div></div>;
    }
    return (
      <div className="page wide">
        <a className="backlink" href="#/portfolio">{IC.chevL} กลับ Portfolio</a>
        <header><div className="eyebrow">Brief · กำลังพัฒนา (B-3)</div><h1 className="page-title">{p.name}</h1></header>
        <div className="rail-card" style={{ padding: 24, textAlign: "center" }}>
          <p style={{ fontSize: 14, color: "var(--muted)" }}>หน้า Project Brief จะถูกพัฒนาในเฟส B-3</p>
          <p style={{ fontSize: 13, color: "var(--faint)", marginTop: 8 }}>ระหว่างนี้สามารถเปิดมุมมองรายละเอียดได้ที่:</p>
          <a className="btn pri" href={"#/project/" + p.id} style={{ marginTop: 12, display: "inline-flex" }}>เปิดคอนโซลผู้ดูแล (Admin Detail) →</a>
        </div>
      </div>
    );
  };

  // ── Main screen ─────────────────────────────────────────────
  window.SCREENS.portfolio = function PortfolioScreen() {
    window.useLiveData();
    const [view, setView] = useState(() => isMobile() ? "card" : "list");
    const [q, setQ] = useState("");
    const canEdit = window.can ? window.can("editProject") : false;

    // Active projects (not completed) — sorted by byPortfolio
    const all = D.projects || [];
    const active = all.filter((p) => p.status !== "completed");
    const sorted = window.sortPortfolio ? window.sortPortfolio(active) : active.slice();
    const list = q.trim()
      ? sorted.filter((p) => (p.name + " " + (p.code || "") + " " + (p.owner || "")).toLowerCase().includes(q.toLowerCase()))
      : sorted;

    const starredCt = active.filter((p) => p.starred).length;
    const overdueCt = active.filter((p) => p.end && p.end < (window.todayISO ? window.todayISO() : "")).length;

    return (
      <div className="page wide exec-screen">
        <header>
          <div className="eyebrow">Portfolio</div>
          <h1 className="page-title">โครงการ <span className="tnum" style={{ color: "var(--muted)", fontWeight: 400, fontSize: 18 }}>({active.length})</span></h1>
          <p className="page-sub">
            {starredCt > 0 && <>★ ปักหมุด {starredCt} · </>}
            {overdueCt > 0 && <span style={{ color: "var(--danger)", fontWeight: 600 }}>เลยกำหนด {overdueCt} · </span>}
            เรียงโดยการปักหมุด · กำหนดส่ง · ความสำคัญ · ความคืบหน้า
          </p>
        </header>

        <div className="toolbar" style={{ flexWrap: "wrap" }}>
          <div className="seg" role="tablist" aria-label="View mode">
            <button className={view === "list" ? "on" : ""} onClick={() => setView("list")} title="List view">{IC.layers} List</button>
            <button className={view === "card" ? "on" : ""} onClick={() => setView("card")} title="Card view">{IC.grid} Card</button>
            <button className={view === "gantt" ? "on" : ""} onClick={() => setView("gantt")} title="Gantt view">{IC.gantt} Gantt</button>
          </div>
          <div className="spacer" />
          <div className="chip" style={{ flex: "1 1 200px", maxWidth: 320, padding: "0 13px" }}>
            {IC.search}
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="ค้นหาโครงการ, รหัส, เจ้าของ…"
              style={{ border: 0, background: "none", outline: "none", font: "inherit", fontSize: 14, flex: 1, color: "var(--ink)", height: 40 }} />
          </div>
        </div>

        {q.trim() && list.length === 0 && (
          <window.EmptyState icon="search" title={"ไม่พบผลลัพธ์สำหรับ \"" + q + "\""} sub="ลองคำค้นอื่นหรือล้างตัวกรอง" />
        )}

        {(!q.trim() || list.length > 0) && (
          <div style={{ marginTop: 8 }}>
            {view === "list"  && <ListView  projects={list} canEdit={canEdit} />}
            {view === "card"  && <CardView  projects={list} canEdit={canEdit} />}
            {view === "gantt" && <GanttView projects={list} />}
          </div>
        )}
      </div>
    );
  };
})();
