const Dashboard = ({ pieces, onNav, setOpenPieceId }) => {
  const today = new Date();
  const dow = today.getDay();
  const monday = new Date(today);
  monday.setDate(today.getDate() - (dow === 0 ? 6 : dow - 1));
  monday.setHours(0, 0, 0, 0);
  const sunday = new Date(monday);
  sunday.setDate(monday.getDate() + 6);
  sunday.setHours(23, 59, 59, 999);

  const thisWeek = pieces
    .filter(p => {
      if (!p.scheduledDate) return false;
      const d = new Date(p.scheduledDate + "T12:00:00");
      return d >= monday && d <= sunday;
    })
    .sort((a, b) => a.scheduledDate.localeCompare(b.scheduledDate));

  const needsApproval = pieces.filter(p => p.stage === "Ready for Review" && !p.approved);

  const weekLabel = `${monday.toLocaleDateString("en-US", { month: "short", day: "numeric" })} – ${sunday.toLocaleDateString("en-US", { month: "short", day: "numeric" })}`;

  const openPiece = (p) => {
    setOpenPieceId(p.id);
    onNav(p.scheduledDate ? "calendar" : "pipeline");
  };

  return (
    <div>
      <div className="pagehead">
        <div>
          <div className="eyebrow">Overview</div>
          <h1 className="serif">Good {getGreeting()}, Yuri.</h1>
          <p className="sub">{today.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" })}</p>
        </div>
      </div>

      <div className="dash-sections">

        <section className="dash-section">
          <div className="dash-section-head">
            <h3 className="serif">This week</h3>
            <span className="dash-section-meta">{weekLabel}</span>
            <button className="btn btn-ghost btn-sm" style={{ marginLeft: "auto" }} onClick={() => onNav("calendar")}>
              Calendar →
            </button>
          </div>
          {thisWeek.length === 0 ? (
            <div className="dash-empty">
              Nothing scheduled this week.{" "}
              <button className="inline-link" onClick={() => onNav("calendar")}>Go to calendar →</button>
            </div>
          ) : (
            <div className="dash-list">
              {thisWeek.map(p => (
                <div key={p.id} className="dash-item" onClick={() => openPiece(p)}>
                  <div className="dash-item-date">{formatDate(p.scheduledDate)}</div>
                  <div className="dash-item-body">
                    <div className="dash-item-title">{p.title}</div>
                    <div style={{ display: "flex", gap: 6, alignItems: "center", marginTop: 4 }}>
                      <FormatBadge format={p.format} />
                      {p.niche && <NicheTag niche={p.niche} size="sm" />}
                    </div>
                  </div>
                  <span className={`pill ${p.approved ? "pill-approved" : p.stage === "Ready for Review" ? "pill-ready" : "pill-draft"}`}>
                    {p.approved ? "Approved" : p.stage}
                  </span>
                </div>
              ))}
            </div>
          )}
        </section>

        {needsApproval.length > 0 && (
          <section className="dash-section">
            <div className="dash-section-head">
              <h3 className="serif">Needs approval</h3>
              <span className="dash-section-meta">{needsApproval.length} waiting</span>
              <button className="btn btn-ghost btn-sm" style={{ marginLeft: "auto" }} onClick={() => onNav("pipeline")}>
                Pipeline →
              </button>
            </div>
            <div className="dash-list">
              {needsApproval.map(p => (
                <div key={p.id} className="dash-item" onClick={() => openPiece(p)}>
                  <div className="dash-item-date"><FormatBadge format={p.format} /></div>
                  <div className="dash-item-body">
                    <div className="dash-item-title">{p.title}</div>
                    {p.niche && <div style={{ marginTop: 4 }}><NicheTag niche={p.niche} size="sm" /></div>}
                  </div>
                  <span className="pill pill-ready">Review</span>
                </div>
              ))}
            </div>
          </section>
        )}

        {needsApproval.length === 0 && thisWeek.length === 0 && (
          <div className="dash-empty" style={{ textAlign: "center", padding: "60px 0" }}>
            <div style={{ fontSize: "2rem", marginBottom: 12 }}>✦</div>
            <p>Nothing scheduled this week and no approvals waiting.</p>
            <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 16 }}>
              <button className="btn btn-primary" onClick={() => onNav("calendar")}>Open calendar</button>
              <button className="btn btn-ghost" onClick={() => onNav("pipeline")}>View pipeline</button>
            </div>
          </div>
        )}

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

window.Dashboard = Dashboard;
