// ---------- Project Detail — the heart of HarborDock ----------

function initialsFromName(name) {
  return (name || "")
    .replace(/\/.*/, "")
    .split(/\s+/)
    .filter(Boolean)
    .map((part) => part[0])
    .slice(0, 2)
    .join("")
    .toUpperCase() || "HD";
}

function getProjectDetail(projectId) {
  const base = HD.projects.find((project) => project.id === projectId);
  if (!base || base.id === HD.projectDetail.id) return HD.projectDetail;

  return {
    ...HD.projectDetail,
    ...base,
    agency: HD.projectDetail.agency,
    synopsis: `${base.name} is currently in ${base.phase || base.statusLabel}. This demo uses the shared review workspace template until live project detail records are connected.`,
    reviewers: [
      {
        name: base.client,
        role: "Client lead",
        initials: initialsFromName(base.client),
        accent: base.accent,
      },
    ],
    drafts: HD.projectDetail.drafts.map((draft) => ({
      ...draft,
      note: draft.id === "d1" ? `${base.phase || base.statusLabel} review package` : draft.note,
    })),
    comments: HD.projectDetail.comments.map((comment) => ({
      ...comment,
      id: `${base.id}-${comment.id}`,
    })),
  };
}

const ProjectDetailPage = ({ projectId, onBack, onNavigate, onOpenMobileMenu }) => {
  const project = getProjectDetail(projectId);
  const [tab, setTab] = React.useState("overview");

  const tabs = [
    { id: "overview", label: "Overview" },
    { id: "uploads",  label: "Uploads",      count: project.uploads.length },
    { id: "drafts",   label: "Drafts",       count: project.drafts.length },
    { id: "comments", label: "Comments",     count: project.comments.length },
    { id: "revisions",label: "Revisions",    count: project.revisions.length },
    { id: "deliverables", label: "Deliverables", count: project.deliverables.length },
  ];

  return (
    <div>
      <Topbar
        breadcrumbs={["Projects", project.name]}
        title={project.name}
        onOpenMobileMenu={onOpenMobileMenu}
        actions={
          <>
            <Button variant="ghost" size="md" icon={<window.Icon.Share size={13} />} onClick={() => window.dispatchEvent(new CustomEvent("hd-share-portal", { detail: { clientId: project.clientId } }))}>Share portal</Button>
            <Button variant="primary" size="md" icon={<window.Icon.Upload size={13} />} onClick={() => window.ToastEvents.emit({ kind: "upload", title: "Upload draft", body: "Drop a file from your NLE — demo only." })}>Upload draft</Button>
          </>
        }
        tabs={tabs}
        activeTab={tab}
        onTabChange={setTab}
      />

      <div style={{ padding: "24px 32px 80px" }}>
        {/* Project header band */}
        <ProjectHeaderBand project={project} />

        {tab === "overview" && <OverviewTab project={project} setTab={setTab} />}
        {tab === "uploads" && <UploadsTab project={project} />}
        {tab === "drafts" && <DraftsTab project={project} />}
        {tab === "comments" && <CommentsTab project={project} />}
        {tab === "revisions" && <RevisionsTab project={project} />}
        {tab === "deliverables" && <DeliverablesTab project={project} />}
      </div>
    </div>
  );
};

const ProjectHeaderBand = ({ project }) => {
  const tone = STATUS_TONES[project.accent];
  return (
    <Card style={{ padding: 0, overflow: "hidden", marginBottom: 24 }}>
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 0 }}>
        {/* Thumb */}
        <div style={{
          position: "relative",
          background: `linear-gradient(135deg, var(--charcoal), ${tone.bg})`,
          borderRight: "1px solid rgba(255,255,255,0.04)",
        }}>
          <svg width="100%" height="100%" viewBox="0 0 280 200" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, opacity: 0.18 }}>
            {Array.from({ length: 16 }).map((_, i) => {
              const y = 10 + i * 12;
              return <path key={i} d={`M -10 ${y} Q 70 ${y - 5} 140 ${y} T 290 ${y}`} stroke="white" fill="none" strokeWidth="0.5" />;
            })}
          </svg>
          <div style={{
            position: "absolute", inset: 0,
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <div style={{
              width: 56, height: 56, borderRadius: 99,
              background: "rgba(0,0,0,0.4)", backdropFilter: "blur(8px)",
              border: "1px solid rgba(255,255,255,0.16)",
              display: "flex", alignItems: "center", justifyContent: "center", color: "var(--white)",
            }}><window.Icon.Play size={18} /></div>
          </div>
          <span className="mono" style={{
            position: "absolute", bottom: 12, right: 12,
            background: "rgba(0,0,0,0.5)", border: "1px solid rgba(255,255,255,0.12)",
            color: "var(--white)", padding: "2px 7px", borderRadius: 4, fontSize: 10.5,
          }}>02:18</span>
        </div>

        <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16 }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                <StatusBadge status={project.status} />
                <span className="mono" style={{ fontSize: 11, color: "var(--warm-gray)" }}>{project.code}</span>
                <span style={{ fontSize: 11, color: "var(--warm-gray)" }}>· {project.type}</span>
              </div>
              <p style={{ fontSize: 14, color: "rgba(250,250,250,0.78)", lineHeight: 1.55, margin: "8px 0 0", maxWidth: 720 }}>
                {project.synopsis}
              </p>
            </div>
          </div>

          {/* Header stats */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gridAutoRows: "1fr", gap: 0, paddingTop: 16, borderTop: "1px solid rgba(255,255,255,0.05)" }}>
            <HeaderStat label="CLIENT" value={project.client} />
            <HeaderStat label="PHASE" value={project.phase} />
            <HeaderStat label="LEAD EDITOR" value={project.leadEditor} />
            <HeaderStat label="DUE" value={project.due} sub={`in ${project.dueIn}`} />
            <HeaderStat label="ASSETS" value={project.assets} sub="46 this week" />
          </div>
        </div>
      </div>
    </Card>
  );
};

const HeaderStat = ({ label, value, sub }) => (
  <div style={{ padding: "0 16px", borderRight: "1px solid rgba(255,255,255,0.04)", minWidth: 0, minHeight: 56 }}>
    <div className="micro" style={{ color: "var(--warm-gray)", fontSize: 9.5, marginBottom: 6 }}>{label}</div>
    <div style={{ fontSize: 13.5, fontWeight: 500, color: "var(--white)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }} title={value}>{value}</div>
    {sub && <div style={{ fontSize: 11, color: "var(--warm-gray)", marginTop: 2 }}>{sub}</div>}
  </div>
);

// =========== OVERVIEW TAB ===========
const OverviewTab = ({ project, setTab }) => (
  <div className="hd-fadeUp" style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 24 }}>
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      {/* Production timeline */}
      <Card style={{ padding: 24 }}>
        <SectionHeader eyebrow="PRODUCTION TIMELINE" title="Six-stage cadence" />
        <div style={{ position: "relative", paddingTop: 8 }}>
          <div style={{ position: "absolute", top: 28, left: 8, right: 8, height: 1, background: "rgba(255,255,255,0.06)" }} />
          <div style={{ display: "grid", gridTemplateColumns: `repeat(${project.timeline.length}, 1fr)`, gap: 0 }}>
            {project.timeline.map((t, i) => (
              <div key={i} style={{ textAlign: "center", position: "relative" }}>
                <div style={{
                  width: 14, height: 14, borderRadius: 99, margin: "0 auto",
                  background: t.state === "done" ? "var(--harbor)" : t.state === "active" ? "var(--white)" : "var(--charcoal)",
                  border: t.state === "active" ? "2px solid var(--harbor)" : "2px solid rgba(255,255,255,0.10)",
                  boxShadow: t.state === "active" ? "0 0 0 4px rgba(29,78,216,0.18)" : "none",
                  position: "relative", zIndex: 1,
                }}>
                  {t.state === "done" && (
                    <window.Icon.Check size={8} stroke={3} color="white" style={{ marginTop: -2 }} />
                  )}
                </div>
                <div style={{
                  fontSize: 11, fontWeight: 500,
                  color: t.state === "done" || t.state === "active" ? "var(--white)" : "var(--warm-gray)",
                  marginTop: 14,
                }}>{t.title}</div>
                <div className="mono" style={{ fontSize: 10, color: "var(--warm-gray)", marginTop: 4 }}>{t.date}</div>
              </div>
            ))}
          </div>
        </div>
      </Card>

      {/* Latest draft + comments preview */}
      <Card style={{ padding: 0 }}>
        <div style={{ padding: "20px 24px", borderBottom: "1px solid rgba(255,255,255,0.05)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div className="micro" style={{ color: "var(--warm-gray)", marginBottom: 4 }}>CURRENT REVIEW</div>
            <div style={{ fontSize: 15, fontWeight: 600 }}>Cut 03 — Hero film</div>
          </div>
          <Button variant="ghost" size="sm" onClick={() => setTab("drafts")}>Open in review</Button>
        </div>
        <div style={{ padding: 24 }}>
          <ReviewPlayer project={project} />
        </div>
      </Card>

      {/* Recent comments preview */}
      <Card style={{ padding: 0 }}>
        <div style={{ padding: "18px 20px", borderBottom: "1px solid rgba(255,255,255,0.05)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div className="micro" style={{ color: "var(--warm-gray)", marginBottom: 4 }}>FROM THE CLIENT</div>
            <div style={{ fontSize: 15, fontWeight: 600 }}>Latest comments</div>
          </div>
          <Button variant="ghost" size="sm" onClick={() => setTab("comments")}>See all</Button>
        </div>
        <div>
          {project.comments.slice(0, 3).map((c, i) => (
            <CommentRow key={c.id} comment={c} last={i === 2} dense />
          ))}
        </div>
      </Card>
    </div>

    {/* Right rail */}
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Card style={{ padding: 20 }}>
        <SectionHeader eyebrow="STUDIO" title="Team" dense />
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {project.team.map(p => (
            <div key={p.name} style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <Avatar initials={p.initials} accent={p.accent} size={30} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--white)" }}>{p.name}</div>
                <div style={{ fontSize: 11, color: "var(--warm-gray)" }}>{p.role}</div>
              </div>
            </div>
          ))}
        </div>
        <Divider style={{ margin: "16px 0" }} />
        <div className="micro" style={{ color: "var(--warm-gray)", marginBottom: 10 }}>CLIENT REVIEWERS</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {project.reviewers.map(p => (
            <div key={p.name} style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <Avatar initials={p.initials} accent={p.accent} size={30} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--white)" }}>{p.name}</div>
                <div style={{ fontSize: 11, color: "var(--warm-gray)" }}>{p.role}</div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      <Card style={{ padding: 20 }}>
        <SectionHeader eyebrow="HEALTH" title="Project pulse" dense />
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Pulse label="Approval velocity" value="2.4d avg" tone="green" detail="—0.6d vs studio avg" />
          <Pulse label="Open feedback" value={`${project.comments.filter(c => c.state === "open").length} threads`} tone="amber" detail="3 awaiting reply" />
          <Pulse label="Revision rounds" value="3 active" tone="harbor" detail="below 5-round limit" />
          <Pulse label="Storage used" value="42 GB" tone="teal" detail="of 100 GB plan" />
        </div>
      </Card>

      <Card style={{ padding: 20 }}>
        <SectionHeader eyebrow="LINKS" title="Quick actions" dense />
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <QuickLink iconName="Link" title="Client portal link" sub={`harbor.dk/p/${project.clientId || "sarkis"}`} onClick={() => window.dispatchEvent(new CustomEvent("hd-share-portal", { detail: { clientId: project.clientId } }))} />
          <QuickLink iconName="Send" title="Request more assets" sub="Send client intake form" />
          <QuickLink iconName="Download" title="Export project archive" sub="ZIP with assets + comments" />
          <QuickLink iconName="Lock" title="Set delivery NDA" sub="Currently: standard MSA" />
        </div>
      </Card>
    </div>
  </div>
);

const Pulse = ({ label, value, tone, detail }) => {
  const t = STATUS_TONES[tone];
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
        <span style={{ fontSize: 12, color: "var(--warm-gray)" }}>{label}</span>
        <span style={{ fontSize: 13, fontWeight: 500, color: t.fg }}>{value}</span>
      </div>
      <div style={{ fontSize: 10.5, color: "var(--warm-gray)" }}>{detail}</div>
    </div>
  );
};

const QuickLink = ({ iconName, title, sub, onClick }) => {
  const IconComp = window.Icon[iconName];
  return (
    <button onClick={onClick} className="hd-row" style={{
      display: "flex", alignItems: "center", gap: 10, width: "100%",
      padding: "8px 10px", borderRadius: 8, background: "transparent",
      border: "1px solid transparent", cursor: "pointer", textAlign: "left",
      transition: "background 120ms ease, border-color 120ms ease",
      color: "var(--white)", fontFamily: "var(--sans)",
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 7,
        background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.06)",
        color: "var(--warm-gray)",
        display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
      }}><IconComp size={13} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--white)" }}>{title}</div>
        <div style={{ fontSize: 10.5, color: "var(--warm-gray)" }}>{sub}</div>
      </div>
      <window.Icon.ChevronR size={11} color="var(--warm-gray)" />
    </button>
  );
};

// =========== VIDEO REVIEW PLAYER ===========
const ReviewPlayer = ({ project }) => {
  const [playing, setPlaying] = React.useState(false);
  const [progress, setProgress] = React.useState(33);

  // Comment markers along the scrubber
  const markers = project.comments.map(c => {
    const [m, s] = c.time.split(":").map(Number);
    const seconds = m * 60 + s;
    const pct = (seconds / 138) * 100; // 02:18 total
    return { ...c, pct };
  });

  return (
    <div>
      {/* Player surface */}
      <div style={{
        position: "relative", aspectRatio: "16/9", borderRadius: 10, overflow: "hidden",
        background: "linear-gradient(135deg, #0B0F13, #1D4ED8 240%)",
        border: "1px solid rgba(255,255,255,0.08)",
      }}>
        {/* Topographic lines */}
        <svg width="100%" height="100%" viewBox="0 0 800 450" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, opacity: 0.10 }}>
          {Array.from({ length: 24 }).map((_, i) => {
            const y = 10 + i * 20;
            return <path key={i} d={`M -20 ${y} Q 200 ${y - 10} 400 ${y} T 820 ${y}`} stroke="white" fill="none" strokeWidth="0.5" />;
          })}
        </svg>

        {/* Active comment pin */}
        <div style={{
          position: "absolute", left: "62%", top: "38%",
          width: 28, height: 28, borderRadius: 99,
          background: "var(--amber)", color: "white",
          border: "2px solid rgba(0,0,0,0.4)",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 11, fontWeight: 600,
        }} className="hd-pulse">
          2
        </div>

        {/* Play overlay */}
        <button
          onClick={() => setPlaying(!playing)}
          style={{
            position: "absolute", inset: 0, background: "transparent", border: "none",
            display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
          }}>
          <div style={{
            width: 64, height: 64, borderRadius: 99,
            background: "rgba(0,0,0,0.5)", backdropFilter: "blur(12px)",
            border: "1px solid rgba(255,255,255,0.16)",
            display: "flex", alignItems: "center", justifyContent: "center", color: "var(--white)",
          }}>
            {playing ? <window.Icon.Pause size={22} /> : <window.Icon.Play size={22} />}
          </div>
        </button>

        {/* Top right meta */}
        <div style={{
          position: "absolute", top: 14, right: 14,
          display: "flex", gap: 6,
        }}>
          <span className="mono" style={{
            background: "rgba(0,0,0,0.4)", border: "1px solid rgba(255,255,255,0.12)",
            color: "var(--white)", padding: "2px 7px", borderRadius: 4, fontSize: 10.5,
          }}>3840 × 2160 · ProRes</span>
        </div>

        {/* Top left */}
        <div style={{ position: "absolute", top: 14, left: 14 }}>
          <StatusBadge tone="harbor" label="Cut 03" size="sm" />
        </div>
      </div>

      {/* Scrubber + comment markers */}
      <div style={{ marginTop: 14, padding: "12px 14px", background: "rgba(255,255,255,0.025)", borderRadius: 8, border: "1px solid rgba(255,255,255,0.05)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <button onClick={() => setPlaying(!playing)} style={{
            width: 32, height: 32, borderRadius: 99,
            background: "var(--harbor)", color: "white", border: "none", cursor: "pointer",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>{playing ? <window.Icon.Pause size={12} /> : <window.Icon.Play size={12} />}</button>

          <span className="mono" style={{ fontSize: 11.5, color: "var(--white)" }}>00:45</span>

          {/* Track */}
          <div style={{ flex: 1, height: 16, position: "relative" }}>
            <div style={{
              position: "absolute", left: 0, right: 0, top: "50%", transform: "translateY(-50%)",
              height: 4, background: "rgba(255,255,255,0.08)", borderRadius: 99,
            }} />
            <div style={{
              position: "absolute", left: 0, top: "50%", transform: "translateY(-50%)",
              height: 4, background: "var(--harbor)", borderRadius: 99,
              width: `${progress}%`,
            }} />
            {/* Comment markers */}
            {markers.map(m => (
              <div key={m.id} title={`${m.author}: ${m.body}`} style={{
                position: "absolute", top: "50%", transform: "translate(-50%, -50%)",
                left: `${m.pct}%`,
                width: 14, height: 14, borderRadius: 99,
                background: m.state === "resolved" ? "rgba(34,197,94,0.85)" : "var(--amber)",
                border: "2px solid var(--ink)",
                cursor: "pointer", boxShadow: "0 0 0 1px rgba(255,255,255,0.10)",
              }} />
            ))}
            {/* Playhead */}
            <div style={{
              position: "absolute", top: "50%", left: `${progress}%`, transform: "translate(-50%, -50%)",
              width: 12, height: 12, borderRadius: 99, background: "var(--white)",
              boxShadow: "0 0 0 3px rgba(29,78,216,0.30)",
              cursor: "grab",
            }} />
          </div>

          <span className="mono" style={{ fontSize: 11.5, color: "var(--warm-gray)" }}>02:18</span>
        </div>
      </div>

      {/* Comment input */}
      <div style={{ marginTop: 14, display: "flex", gap: 10, alignItems: "center", padding: 12, background: "rgba(255,255,255,0.025)", borderRadius: 8, border: "1px solid rgba(255,255,255,0.05)" }}>
        <Avatar initials="WM" accent="harbor" size={28} />
        <input
          placeholder="Add a comment at 00:45…"
          style={{
            flex: 1, background: "transparent", border: "none", outline: "none",
            color: "var(--white)", fontSize: 13, fontFamily: "var(--sans)",
          }}
        />
        <Kbd>@</Kbd>
        <span style={{ fontSize: 11, color: "var(--warm-gray)" }}>to mention</span>
        <Button variant="primary" size="sm" icon={<window.Icon.Send size={12} />}>Comment</Button>
      </div>
    </div>
  );
};

// =========== UPLOADS TAB ===========
const UploadsTab = ({ project }) => {
  const [view, setView] = React.useState("grid");
  return (
    <div className="hd-fadeUp" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* Intake widget */}
      <Card style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 0 }}>
          <IntakeStat label="Client uploads" value="4" detail="of 6 expected" tone="harbor" />
          <IntakeStat label="Storage used" value="34.4 GB" detail="42% of plan" tone="teal" />
          <IntakeStat label="Last received" value="Today" detail="Drone aerials, 3.6 GB" tone="amber" />
        </div>
      </Card>

      <Card style={{ padding: 0 }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid rgba(255,255,255,0.05)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <SectionHeader eyebrow={`PROJECT ASSETS · ${project.uploads.length}`} title="Received from team + client" dense />
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <FilterSelect label="Type" value="All" />
            <FilterSelect label="Uploader" value="Anyone" />
            <div style={{ display: "flex", gap: 4, padding: 3, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.05)", borderRadius: 8 }}>
              <ViewToggle active={view === "grid"} onClick={() => setView("grid")} iconName="Grid" label="" />
              <ViewToggle active={view === "list"} onClick={() => setView("list")} iconName="List" label="" />
            </div>
            <Button variant="primary" size="sm" icon={<window.Icon.Upload size={12} />}>Upload</Button>
          </div>
        </div>

        {view === "grid" ? (
          <div style={{ padding: 20, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
            {project.uploads.map(u => <UploadCard key={u.id} upload={u} />)}
            <DropZone />
          </div>
        ) : (
          <div>
            {project.uploads.map((u, i) => <UploadRow key={u.id} upload={u} last={i === project.uploads.length - 1} />)}
          </div>
        )}
      </Card>
    </div>
  );
};

const IntakeStat = ({ label, value, detail, tone }) => {
  const t = STATUS_TONES[tone];
  return (
    <div style={{ padding: 20, borderRight: "1px solid rgba(255,255,255,0.05)", position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", top: -10, right: -10, width: 80, height: 80, borderRadius: "50%", background: t.bg, filter: "blur(40px)" }} />
      <div className="micro" style={{ color: "var(--warm-gray)", marginBottom: 8, position: "relative" }}>{label}</div>
      <div className="serif" style={{ fontSize: 28, color: "var(--white)", letterSpacing: "-0.01em", position: "relative" }}>{value}</div>
      <div style={{ fontSize: 12, color: "var(--warm-gray)", marginTop: 4, position: "relative" }}>{detail}</div>
    </div>
  );
};

const TYPE_ICONS = { video: "Film", image: "Image", audio: "Mic", doc: "File" };
const TYPE_ACCENTS = { video: "harbor", image: "amber", audio: "lavender", doc: "teal" };

const UploadCard = ({ upload }) => {
  const tone = STATUS_TONES[TYPE_ACCENTS[upload.type]];
  const IconComp = window.Icon[TYPE_ICONS[upload.type]];
  return (
    <Card hover style={{ padding: 0, overflow: "hidden" }}>
      <div style={{
        aspectRatio: "16/10", position: "relative",
        background: `linear-gradient(135deg, var(--charcoal), ${tone.bg})`,
        borderBottom: "1px solid rgba(255,255,255,0.04)",
      }}>
        <svg width="100%" height="100%" viewBox="0 0 320 200" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, opacity: 0.16 }}>
          {Array.from({ length: 12 }).map((_, i) => {
            const y = 14 + i * 16;
            return <path key={i} d={`M -10 ${y} Q 80 ${y - 4} 160 ${y} T 340 ${y}`} stroke="white" fill="none" strokeWidth="0.5" />;
          })}
        </svg>
        <div style={{
          position: "absolute", inset: 0,
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 99,
            background: "rgba(0,0,0,0.4)", border: "1px solid rgba(255,255,255,0.16)",
            color: "var(--white)",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}><IconComp size={16} /></div>
        </div>
        <span className="mono" style={{
          position: "absolute", bottom: 10, right: 10,
          background: "rgba(0,0,0,0.5)", border: "1px solid rgba(255,255,255,0.12)",
          color: "var(--white)", padding: "2px 6px", borderRadius: 4, fontSize: 10,
        }}>{upload.size}</span>
      </div>
      <div style={{ padding: 14 }}>
        <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--white)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{upload.name}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 6, fontSize: 11, color: "var(--warm-gray)" }}>
          <Avatar initials={upload.uploader.split(" ").map(s => s[0]).slice(0,2).join("")} accent={tone === STATUS_TONES.harbor ? "harbor" : "neutral"} size={16} />
          <span>{upload.uploader}</span>
          <span>·</span>
          <span>{upload.at.split(",")[0]}</span>
        </div>
        {upload.note && (
          <div style={{
            fontSize: 11, color: "rgba(250,250,250,0.65)",
            background: "rgba(255,255,255,0.025)", border: "1px solid rgba(255,255,255,0.05)",
            borderRadius: 6, padding: "6px 8px", marginTop: 10, lineHeight: 1.4,
          }}>“{upload.note}”</div>
        )}
      </div>
    </Card>
  );
};

const UploadRow = ({ upload, last }) => {
  const tone = STATUS_TONES[TYPE_ACCENTS[upload.type]];
  const IconComp = window.Icon[TYPE_ICONS[upload.type]];
  return (
    <div className="hd-row" style={{
      display: "grid", gridTemplateColumns: "32px minmax(0,2fr) minmax(0,1fr) 110px 90px 30px",
      gap: 16, padding: "12px 20px", alignItems: "center",
      borderBottom: last ? "none" : "1px solid rgba(255,255,255,0.04)",
      cursor: "pointer",
    }}>
      <div style={{ width: 32, height: 32, borderRadius: 6, background: tone.bg, border: `1px solid ${tone.bd}`, color: tone.fg, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <IconComp size={14} />
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--white)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{upload.name}</div>
        {upload.note && <div style={{ fontSize: 11, color: "var(--warm-gray)", marginTop: 2 }}>{upload.note}</div>}
      </div>
      <div style={{ fontSize: 12, color: "rgba(250,250,250,0.78)" }}>{upload.uploader}</div>
      <div style={{ fontSize: 12, color: "var(--warm-gray)" }}>{upload.at}</div>
      <div className="mono" style={{ fontSize: 11.5, color: "var(--white)" }}>{upload.size}</div>
      <window.IconButton iconName="More" />
    </div>
  );
};

const DropZone = () => (
  <div style={{
    border: "1px dashed rgba(255,255,255,0.16)", borderRadius: 14,
    padding: 24, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
    background: "rgba(255,255,255,0.015)", minHeight: 240, textAlign: "center",
  }}>
    <div style={{
      width: 44, height: 44, borderRadius: 12,
      background: "rgba(29,78,216,0.10)", border: "1px solid rgba(29,78,216,0.30)",
      color: "var(--harbor-2)",
      display: "flex", alignItems: "center", justifyContent: "center",
    }}><window.Icon.Upload size={18} /></div>
    <div style={{ fontSize: 13, fontWeight: 500, color: "var(--white)", marginTop: 14 }}>Drop assets to upload</div>
    <div style={{ fontSize: 11.5, color: "var(--warm-gray)", marginTop: 4 }}>Or paste a Frame.io / Drive link</div>
    <Button variant="ghost" size="sm" style={{ marginTop: 14 }}>Browse files</Button>
  </div>
);

// =========== DRAFTS TAB ===========
const DraftsTab = ({ project }) => {
  const [selected, setSelected] = React.useState(project.drafts[0].id);
  const active = project.drafts.find(d => d.id === selected);

  return (
    <div className="hd-fadeUp" style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 16 }}>
      {/* Version history */}
      <Card style={{ padding: 0 }}>
        <div style={{ padding: "16px 18px", borderBottom: "1px solid rgba(255,255,255,0.05)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <SectionHeader eyebrow="VERSION HISTORY" title={`${project.drafts.length} drafts`} dense />
          <Button variant="primary" size="sm" icon={<window.Icon.Plus size={12} />}>New</Button>
        </div>
        <div style={{ padding: 8 }}>
          {project.drafts.map(d => (
            <button
              key={d.id}
              onClick={() => setSelected(d.id)}
              style={{
                display: "flex", alignItems: "flex-start", gap: 12,
                width: "100%", textAlign: "left", padding: 12,
                background: selected === d.id ? "rgba(29,78,216,0.10)" : "transparent",
                border: selected === d.id ? "1px solid rgba(29,78,216,0.28)" : "1px solid transparent",
                borderRadius: 10, cursor: "pointer", marginBottom: 4,
                color: "var(--white)", fontFamily: "var(--sans)",
                transition: "background 120ms ease",
              }}
            >
              <div style={{ width: 64, flexShrink: 0 }}>
                <AssetThumb tone={d.thumb} duration={d.duration} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                  <span style={{ fontSize: 13, fontWeight: 500, color: "var(--white)" }}>{d.version}</span>
                  <StatusBadge status={d.state} size="sm" />
                </div>
                <div style={{ fontSize: 11, color: "var(--warm-gray)", marginBottom: 6 }}>{d.at}</div>
                <div style={{ fontSize: 11.5, color: "rgba(250,250,250,0.65)", lineHeight: 1.4 }}>{d.note}</div>
              </div>
            </button>
          ))}
        </div>
      </Card>

      {/* Active draft player */}
      <Card style={{ padding: 0 }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid rgba(255,255,255,0.05)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div className="micro" style={{ color: "var(--warm-gray)", marginBottom: 4 }}>NOW REVIEWING</div>
            <div style={{ fontSize: 15, fontWeight: 600 }}>{active.version} · {active.duration}</div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <Button variant="ghost" size="sm" icon={<window.Icon.Download size={12} />}>Download</Button>
            <Button variant="ghost" size="sm" icon={<window.Icon.Share size={12} />}>Share</Button>
            <Button variant="primary" size="sm" icon={<window.Icon.Check size={12} />}>Mark approved</Button>
          </div>
        </div>
        <div style={{ padding: 20 }}>
          <ReviewPlayer project={project} />
        </div>
      </Card>
    </div>
  );
};

// =========== COMMENTS TAB ===========
const CommentsTab = ({ project }) => {
  const [filter, setFilter] = React.useState("all");
  const [comments, setComments] = React.useState(project.comments);
  const [composer, setComposer] = React.useState("");
  const filtered = comments.filter(c => filter === "all" || c.state === filter);

  const post = () => {
    if (!composer.trim()) return;
    const newC = {
      id: `c${Date.now()}`,
      author: "Winterhill Media", initials: "WM", role: "agency",
      time: "00:45", body: composer.trim(), state: "open",
      at: "just now", replies: 0,
    };
    setComments([...comments, newC]);
    setComposer("");
    window.ToastEvents.emit({
      kind: "success",
      title: "Comment posted",
      body: `Reply timestamped at 00:45.`,
    });
  };

  const toggleResolve = (id) => {
    setComments(comments.map(c => c.id === id ? { ...c, state: c.state === "open" ? "resolved" : "open" } : c));
    const c = comments.find(x => x.id === id);
    if (c) window.ToastEvents.emit({ kind: "info", title: c.state === "open" ? "Comment resolved" : "Comment reopened", body: c.body.slice(0, 64) + (c.body.length > 64 ? "…" : "") });
  };

  return (
    <div className="hd-fadeUp" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16 }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Card style={{ padding: 0 }}>
          <div style={{ padding: "16px 20px", borderBottom: "1px solid rgba(255,255,255,0.05)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <SectionHeader eyebrow={`THREAD · CUT 03`} title={`${comments.length} comments`} dense />
            <div style={{ display: "flex", gap: 6 }}>
              <FilterChip active={filter === "all"} onClick={() => setFilter("all")}>All</FilterChip>
              <FilterChip active={filter === "open"} onClick={() => setFilter("open")} tone="amber">Open</FilterChip>
              <FilterChip active={filter === "resolved"} onClick={() => setFilter("resolved")} tone="green">Resolved</FilterChip>
            </div>
          </div>
          <div>
            {filtered.map((c, i) => <CommentRow key={c.id} comment={c} last={i === filtered.length - 1} onToggleResolve={toggleResolve} />)}
          </div>
        </Card>

        {/* Compose */}
        <Card style={{ padding: 16 }}>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
            <Avatar initials="WM" accent="harbor" size={32} />
            <div style={{ flex: 1 }}>
              <textarea
                value={composer}
                onChange={(e) => setComposer(e.target.value)}
                onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === "Enter") post(); }}
                placeholder="Reply to the thread, or @mention a teammate…"
                rows={2}
                style={{
                  width: "100%", background: "rgba(255,255,255,0.025)",
                  border: "1px solid rgba(255,255,255,0.06)", borderRadius: 8,
                  padding: 10, color: "var(--white)", fontSize: 13,
                  fontFamily: "var(--sans)", resize: "none", outline: "none",
                  boxSizing: "border-box",
                }}
              />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11, color: "var(--warm-gray)" }}>
                  <window.Icon.Clock size={12} />
                  <span>Posting at <span className="mono" style={{ color: "var(--white)" }}>00:45</span></span>
                  <span style={{ marginLeft: 12 }}><Kbd>⌘</Kbd> <Kbd>↵</Kbd> to post</span>
                </div>
                <Button variant="primary" size="sm" icon={<window.Icon.Send size={12} />} onClick={post}>Post</Button>
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* Right rail: contextual timeline + stats */}
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Card style={{ padding: 20 }}>
          <SectionHeader eyebrow="THREAD HEALTH" title="At a glance" dense />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 4 }}>
            <MiniMetric label="Open" value={comments.filter(c => c.state === "open").length} tone="amber" />
            <MiniMetric label="Resolved" value={comments.filter(c => c.state === "resolved").length} tone="green" />
            <MiniMetric label="Client" value={comments.filter(c => c.role === "client").length} tone="harbor" />
            <MiniMetric label="Studio" value={comments.filter(c => c.role === "agency").length} tone="lavender" />
          </div>
        </Card>

        <Card style={{ padding: 20 }}>
          <SectionHeader eyebrow="COMMENT MAP" title="Cut 03 timecode" dense />
          <TimecodeMap comments={comments} />
        </Card>

        <Card style={{ padding: 20 }}>
          <SectionHeader eyebrow="REVIEWERS" title="On this draft" dense />
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {project.reviewers.map(r => (
              <div key={r.name} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <Avatar initials={r.initials} accent={r.accent} size={28} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>{r.name}</div>
                  <div style={{ fontSize: 11, color: "var(--warm-gray)" }}>{r.role}</div>
                </div>
                <span style={{ width: 6, height: 6, borderRadius: 99, background: "#22C55E" }} />
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
};

const CommentRow = ({ comment, last, dense = false, onToggleResolve }) => {
  const isClient = comment.role === "client";
  return (
    <div style={{
      padding: dense ? "12px 20px" : "16px 20px",
      borderBottom: last ? "none" : "1px solid rgba(255,255,255,0.04)",
      display: "flex", gap: 12,
    }}>
      <Avatar initials={comment.initials} accent={isClient ? "harbor" : "lavender"} size={dense ? 28 : 32} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4, flexWrap: "wrap" }}>
          <span style={{ fontSize: 13, fontWeight: 500, color: "var(--white)" }}>{comment.author}</span>
          <span style={{ fontSize: 10.5, padding: "1px 6px", borderRadius: 99, background: isClient ? "rgba(29,78,216,0.14)" : "rgba(139,92,246,0.14)", color: isClient ? "#9CC1FF" : "#C4A8FF", fontWeight: 500 }}>
            {isClient ? "Client" : "Studio"}
          </span>
          <span className="mono" style={{ fontSize: 10.5, color: "var(--harbor-2)", background: "rgba(29,78,216,0.10)", padding: "1px 6px", borderRadius: 4 }}>{comment.time}</span>
          <span style={{ fontSize: 10.5, color: "var(--warm-gray)" }}>· {comment.at}</span>
          {comment.state === "resolved" && (
            <StatusBadge status="resolved" size="sm" />
          )}
        </div>
        <div style={{ fontSize: dense ? 12.5 : 13.5, color: "rgba(250,250,250,0.85)", lineHeight: 1.55 }}>{comment.body}</div>
        {!dense && (
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 10 }}>
            <button style={{ background: "transparent", border: "none", color: "var(--warm-gray)", fontSize: 11.5, cursor: "pointer", fontFamily: "var(--sans)", display: "inline-flex", alignItems: "center", gap: 4 }}>
              <window.Icon.Message size={11} /> Reply {comment.replies > 0 && `(${comment.replies})`}
            </button>
            <button
              onClick={() => onToggleResolve && onToggleResolve(comment.id)}
              style={{ background: "transparent", border: "none", color: comment.state === "resolved" ? "#86EFAC" : "var(--warm-gray)", fontSize: 11.5, cursor: "pointer", fontFamily: "var(--sans)", display: "inline-flex", alignItems: "center", gap: 4 }}>
              <window.Icon.Check size={11} /> {comment.state === "resolved" ? "Reopen" : "Resolve"}
            </button>
            <button
              onClick={() => window.ToastEvents.emit({ kind: "info", title: "Link copied", body: `Anchored to ${comment.time} on Cut 03.` })}
              style={{ background: "transparent", border: "none", color: "var(--warm-gray)", fontSize: 11.5, cursor: "pointer", fontFamily: "var(--sans)", display: "inline-flex", alignItems: "center", gap: 4 }}>
              <window.Icon.Link size={11} /> Copy link
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

const MiniMetric = ({ label, value, tone }) => {
  const t = STATUS_TONES[tone];
  return (
    <div style={{
      padding: 12, borderRadius: 10,
      background: t.bg, border: `1px solid ${t.bd}`,
    }}>
      <div className="serif" style={{ fontSize: 22, color: t.fg, letterSpacing: "-0.01em" }}>{value}</div>
      <div style={{ fontSize: 11, color: "var(--warm-gray)", marginTop: 2 }}>{label}</div>
    </div>
  );
};

const TimecodeMap = ({ comments }) => {
  // Map comments to dots along a "filmstrip"
  return (
    <div>
      <div style={{ position: "relative", height: 56, marginTop: 4 }}>
        {/* Filmstrip */}
        <div style={{ position: "absolute", inset: "16px 0", borderRadius: 6, background: "linear-gradient(135deg, var(--charcoal), var(--slate))", border: "1px solid rgba(255,255,255,0.06)" }}>
          {Array.from({ length: 18 }).map((_, i) => (
            <div key={i} style={{
              position: "absolute", top: 2, bottom: 2,
              left: `${(i / 18) * 100}%`, width: 1, background: "rgba(255,255,255,0.04)",
            }} />
          ))}
        </div>
        {comments.map(c => {
          const [m, s] = c.time.split(":").map(Number);
          const pct = ((m * 60 + s) / 138) * 100;
          return (
            <div key={c.id} style={{
              position: "absolute", top: "50%", left: `${pct}%`, transform: "translate(-50%, -50%)",
              width: 18, height: 18, borderRadius: 99,
              background: c.state === "resolved" ? "rgba(34,197,94,0.85)" : "var(--amber)",
              border: "2px solid var(--charcoal)",
              display: "flex", alignItems: "center", justifyContent: "center",
              fontSize: 9, color: "white", fontWeight: 600,
            }}>{comments.indexOf(c) + 1}</div>
          );
        })}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 4 }}>
        <span className="mono" style={{ fontSize: 10, color: "var(--warm-gray)" }}>00:00</span>
        <span className="mono" style={{ fontSize: 10, color: "var(--warm-gray)" }}>02:18</span>
      </div>
    </div>
  );
};

// =========== REVISIONS TAB ===========
const RevisionsTab = ({ project }) => (
  <div className="hd-fadeUp" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
      <StatCard label="Total rounds" value="3" detail="Of 5 allotted" tone="harbor" iconName="Layers" />
      <StatCard label="Open items" value="4" detail="2 in progress" tone="amber" iconName="Clock" />
      <StatCard label="Avg round time" value="3.2d" detail="—0.8d vs studio avg" tone="green" iconName="Trend" />
    </div>

    {project.revisions.map((round, i) => <RevisionRound key={i} round={round} />)}

    <Card style={{ padding: 24, textAlign: "center" }}>
      <Button variant="ghost" size="md" icon={<window.Icon.Plus size={13} />}>Start round 04</Button>
    </Card>
  </div>
);

const RevisionRound = ({ round }) => {
  const isActive = round.state === "active";
  return (
    <Card style={{ padding: 0, overflow: "hidden" }}>
      <div style={{
        padding: "16px 20px",
        borderBottom: "1px solid rgba(255,255,255,0.05)",
        background: isActive ? "rgba(29,78,216,0.05)" : "transparent",
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div className="serif" style={{ fontSize: 18, fontWeight: 500, letterSpacing: "-0.01em", color: "var(--white)" }}>{round.round}</div>
            <StatusBadge status={round.state} size="sm" />
          </div>
          <div style={{ fontSize: 12, color: "var(--warm-gray)", marginTop: 4 }}>{round.date}</div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--warm-gray)" }}>
          <window.Icon.Check size={12} />
          <span>{round.items.filter(i => i.state === "done").length} of {round.items.length} complete</span>
        </div>
      </div>
      <div>
        {round.items.map((item, i) => <RevisionItem key={i} item={item} last={i === round.items.length - 1} />)}
      </div>
    </Card>
  );
};

const RevisionItem = ({ item, last }) => (
  <div className="hd-row" style={{
    display: "grid", gridTemplateColumns: "28px minmax(0,1fr) 130px 90px 130px",
    gap: 14, padding: "12px 20px", alignItems: "center",
    borderBottom: last ? "none" : "1px solid rgba(255,255,255,0.04)",
  }}>
    <Checkbox checked={item.state === "done"} />
    <div style={{
      fontSize: 13,
      color: item.state === "done" ? "var(--warm-gray)" : "var(--white)",
      textDecoration: item.state === "done" ? "line-through" : "none",
      fontWeight: 500,
    }}>{item.title}</div>
    <div style={{ fontSize: 12, color: "var(--warm-gray)" }}>{item.owner}</div>
    <div style={{ fontSize: 12, color: "var(--white)" }}>{item.due}</div>
    <StatusBadge status={item.state} size="sm" />
  </div>
);

const Checkbox = ({ checked }) => (
  <div style={{
    width: 18, height: 18, borderRadius: 5,
    background: checked ? "var(--harbor)" : "transparent",
    border: checked ? "1px solid var(--harbor)" : "1px solid rgba(255,255,255,0.20)",
    display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
  }}>
    {checked && <window.Icon.Check size={11} stroke={3} color="white" />}
  </div>
);

// =========== DELIVERABLES TAB ===========
const DeliverablesTab = ({ project }) => {
  const allReady = project.deliverables.filter(d => d.state === "ready" || d.state === "done").length;
  return (
    <div className="hd-fadeUp" style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 16 }}>
      <Card style={{ padding: 0 }}>
        <div style={{ padding: "20px 24px", borderBottom: "1px solid rgba(255,255,255,0.05)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <SectionHeader eyebrow="DELIVERY CHECKLIST" title={`${allReady} of ${project.deliverables.length} ready`} dense />
            <div style={{ fontSize: 12, color: "var(--warm-gray)" }}>Final delivery due May 24</div>
          </div>
          <Button variant="primary" size="md" icon={<window.Icon.Send size={13} />}>Send final package</Button>
        </div>
        <div>
          {project.deliverables.map((d, i) => <DeliverableRow key={d.id} item={d} last={i === project.deliverables.length - 1} />)}
        </div>
      </Card>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Card style={{ padding: 20, position: "relative", overflow: "hidden" }}>
          <div style={{ position: "absolute", top: -30, right: -30, width: 120, height: 120, borderRadius: "50%", background: "rgba(29,78,216,0.16)", filter: "blur(40px)" }} />
          <SectionHeader eyebrow="DELIVERY READINESS" title="Almost there" dense />
          <div style={{ position: "relative", margin: "8px 0 16px" }}>
            <div className="serif" style={{ fontSize: 56, fontWeight: 500, letterSpacing: "-0.025em", color: "var(--white)", lineHeight: 1 }}>
              68<span style={{ fontSize: 24, color: "var(--warm-gray)" }}>%</span>
            </div>
            <Progress value={68} tone="harbor" height={6} />
          </div>
          <div style={{ fontSize: 12, color: "var(--warm-gray)", lineHeight: 1.5 }}>
            Final delivery unlocks once all 5 items reach "Ready" state and client signs the approval log.
          </div>
        </Card>

        <Card style={{ padding: 20 }}>
          <SectionHeader eyebrow="APPROVAL LOG" title="On record" dense />
          <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 4 }}>
            <LogRow author="Roy Bahnam" action="approved square cut" at="May 13, 4:12 PM" />
            <LogRow author="Roy Bahnam" action="approved music direction" at="May 06, 11:30 AM" />
            <LogRow author="Sarkis Team" action="approved color treatment" at="May 11, 2:48 PM" />
            <LogRow author="Roy Bahnam" action="approved selects" at="May 03, 10:14 AM" />
          </div>
        </Card>
      </div>
    </div>
  );
};

const DeliverableRow = ({ item, last }) => (
  <div style={{
    display: "grid", gridTemplateColumns: "44px minmax(0,1fr) 200px 140px 90px",
    gap: 16, padding: "16px 24px", alignItems: "center",
    borderBottom: last ? "none" : "1px solid rgba(255,255,255,0.04)",
  }}>
    <div style={{
      width: 44, height: 44, borderRadius: 10,
      background: "rgba(255,255,255,0.025)", border: "1px solid rgba(255,255,255,0.06)",
      color: "var(--warm-gray)",
      display: "flex", alignItems: "center", justifyContent: "center",
    }}>
      <window.Icon.Film size={16} />
    </div>
    <div>
      <div style={{ fontSize: 13.5, fontWeight: 500, color: "var(--white)" }}>{item.name}</div>
      <div style={{ fontSize: 11.5, color: "var(--warm-gray)", marginTop: 2 }}>{item.note}</div>
    </div>
    <div className="mono" style={{ fontSize: 11.5, color: "var(--white)" }}>{item.format}</div>
    <div style={{ fontSize: 12, color: "var(--warm-gray)" }}>{item.resolution}</div>
    <StatusBadge status={item.state} size="sm" />
  </div>
);

const LogRow = ({ author, action, at }) => (
  <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
    <div style={{
      width: 18, height: 18, borderRadius: 99, background: "rgba(34,197,94,0.20)",
      border: "1px solid rgba(34,197,94,0.40)", color: "#86EFAC",
      display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, marginTop: 2,
    }}>
      <window.Icon.Check size={10} stroke={2.4} />
    </div>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 12.5 }}>
        <span style={{ color: "var(--white)", fontWeight: 500 }}>{author}</span>
        <span style={{ color: "var(--warm-gray)" }}> {action}</span>
      </div>
      <div style={{ fontSize: 10.5, color: "var(--warm-gray)", marginTop: 2 }}>{at}</div>
    </div>
  </div>
);

window.ProjectDetailPage = ProjectDetailPage;
