/* ============ My Workspace (Home) — personal pulse dashboard ============
   Designed to answer: "What was I working on, and what's waiting on me?"
   Approval flow (pending drafts + access requests) is handled inline here
   for Admins; team-lane data lives in Lane View. */

const MyWorkspace = ({ state, nav }) => {
  const me     = CURRENT_ADMIN.id;
  const isAdmin = CURRENT_ADMIN.role === "Admin";

  /* Decline-with-reason modal — req §3.4/§4.10: reason is mandatory.
     { req: singleRequest } */
  const [declineTarget, setDeclineTarget] = React.useState(null);

  /* ---------- Data slices ---------- */

  /* Recent files — across all clients, filtered to my own access events.
     Sorted newest-first. (No "Active Client" filter per spec.) */
  const myRecent = (RECENT_FILES_SEED || [])
    .filter(r => r.accessedBy === me)
    .sort((a,b) => (b.accessedAt||"").localeCompare(a.accessedAt||""))
    .slice(0, 10);

  /* Approval Center slices — embedded on Home for Admin */
  const pendingDrafts   = state.projects.filter(isAwaitingActivation);
  const pendingAccess   = state.accessRequests.filter(r => r.status === "pending");

  /* My to-do — every kind, then bucketed for the tab switcher.
     Definitions (user decision 2026-06-12):
       work-on    → WPIDs I uploaded / am preparing, not yet in review
       respond-rn → WPIDs back on me because review started (RN to answer)
       review     → WPIDs where I'm the reviewer — INCLUDES sign-off, since
                    reviewing ends in either "keep editing" or "sign off"
                    (the old separate To-sign tab was redundant) */
  const myTodo = (HOME_TODO_SEED || []).filter(t => t.assignee === me);
  const todoByKind = {
    "work-on":    myTodo.filter(t => t.kind === "work-on"),
    "respond-rn": myTodo.filter(t => t.kind === "respond-rn"),
    "review":     myTodo.filter(t => t.kind === "review" || t.kind === "sign-off"),
  };
  const todoTotal = myTodo.length;

  /* Active engagements — projects I'm a member of, just condensed */
  const myActive = state.projects.filter(p =>
    p.status === "active" && (p.members.includes(me) || p.approvedBy === me || p.createdBy === me)
  );

  /* ---------- UI helpers ---------- */
  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return "Good morning";
    if (h < 18) return "Good afternoon";
    return "Good evening";
  })();
  const firstName = CURRENT_ADMIN.name.split(" ")[0];

  const openProject = (projectId) => nav.go({ view:"project-structure", projectId });

  /* File-type icon */
  const fileIcon = (type) => {
    const t = (type||"").toLowerCase();
    if (t === "xlsx" || t === "xls" || t === "xlsm" || t === "csv") return "grid";
    if (t === "pdf") return "file-text";
    if (t === "docx" || t === "doc" || t === "txt") return "file";
    return "file";
  };

  /* To-do tab metadata — land on the first tab that actually has items
     (falling back to "work-on" when everything is clear) */
  const [todoTab, setTodoTab] = React.useState(() =>
    ["work-on", "respond-rn", "review"].find(k => todoByKind[k].length > 0) || "work-on"
  );
  /* To review sits rightmost — work-on → respond → review mirrors how a
     WPID actually flows away from me */
  const TODO_TABS = [
    { key:"work-on",    label:"To work on",  icon:"edit-3", count: todoByKind["work-on"].length },
    { key:"respond-rn", label:"To respond",  icon:"send",   count: todoByKind["respond-rn"].length },
    { key:"review",     label:"To review",   icon:"eye",    count: todoByKind["review"].length },
  ];

  /* ---------- Renderers ---------- */

  const renderRecent = () => (
    <div className="sec">
      <div className="sec-head">
        <span className="sec-title"><Icon n="clock" s={14}/> Recent files <span className="badge">{myRecent.length}</span></span>
      </div>
      <div className="sec-body flush">
        {myRecent.length === 0 ? (
          <EmptyState icon="clock" title="No recent files" sub="Files you open will appear here for quick access — no need to dig through projects."/>
        ) : myRecent.map(r => {
          const p   = projectById(r.projectId);
          const e   = p ? entityById(p.entityId) : null;
          return (
            <div key={r.id} className="recent-row" onClick={()=>openProject(r.projectId)}>
              <div style={{display:"grid",placeItems:"center",color:"var(--muted)"}}>
                <Icon n={fileIcon(r.type)} s={16}/>
              </div>
              <div style={{minWidth:0}}>
                <div className="r-name truncate">{r.fileName}</div>
                <div className="r-path truncate">{r.folderPath}</div>
              </div>
              <div style={{display:"flex",alignItems:"center",gap:7,minWidth:0}}>
                {e && <span className="ent-mark" style={{width:22,height:22,fontSize:8.5,background:"var(--ink)"}}>{e.code}</span>}
                <span className="truncate" style={{fontSize:11.5,color:"var(--ink-2)"}}>{p?.name || r.projectId}</span>
              </div>
              <div className="r-when">
                <b className="mono" style={{fontWeight:500,fontSize:11.5}}>{fmtTsShort(r.accessedAt)}</b>
              </div>
              <button className="btn sm ghost r-act" onClick={(ev)=>{ev.stopPropagation();openProject(r.projectId);}}>
                Open <Icon n="chev-r" s={11}/>
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );

  const renderTodoRow = (t) => {
    const p = projectById(t.projectId);
    const e = p ? entityById(p.entityId) : null;
    const when = t.flaggedAt || t.askedAt;
    let titleNode, subNode;

    switch (t.kind) {
      case "work-on":
        titleNode = t.wpidName;
        subNode = <>WPID <span className="mono">{t.wpidId}</span> · {t.folderPath} · {t.reopened ? <span style={{color:"var(--danger-ink)"}}>Review reopened — needs rework</span> : "In progress"}</>;
        break;
      case "review":
        titleNode = t.wpidName;
        subNode = <>WPID <span className="mono">{t.wpidId}</span> · {t.folderPath} · Waiting for your review</>;
        break;
      case "respond-rn":
        titleNode = <>RN: {t.rnSubject}</>;
        subNode = <>Submitted by <b style={{color:"var(--ink-2)"}}>{t.askedByName}</b></>;
        break;
      case "sign-off":
        titleNode = t.wpidName;
        subNode = <>Sign-off as <b style={{color:"var(--ink-2)"}}>{t.role}</b> · WPID <span className="mono">{t.wpidId}</span> · {t.folderPath}</>;
        break;
      default:
        titleNode = t.wpidName || t.rnSubject;
        subNode = t.folderPath;
    }

    return (
      <div key={t.id} className="todo-row" onClick={()=>openProject(t.projectId)}>
        <div style={{display:"grid",placeItems:"center"}}>
          {t.priority === "high"
            ? <Icon n="alert-triangle" s={14} c="" />
            : <Icon n="chev-r" s={14}/>}
        </div>
        <div style={{minWidth:0}}>
          <div className="t-title truncate">{titleNode}</div>
          <div className="t-sub">{subNode}</div>
        </div>
        <div className="t-proj" style={{minWidth:0}}>
          <span className="truncate" style={{display:"inline-flex",alignItems:"center",gap:6}}>
            {e && <span className="ent-mark" style={{width:20,height:20,fontSize:8.5,background:"var(--ink)"}}>{e.code}</span>}
            <span className="truncate" style={{maxWidth:220}}>{p?.name}</span>
          </span>
        </div>
        <div className="t-when mono" style={{fontSize:11}}>{fmtTsShort(when)}</div>
      </div>
    );
  };

  const renderTodo = () => {
    const items = todoByKind[todoTab];
    return (
      <div className="sec">
        <div className="sec-head" style={{gap:0}}>
          <span className="sec-title"><Icon n="flag" s={14}/> My to-do <span className="badge">{todoTotal}</span></span>
          <div className="tabbar-inline">
            {TODO_TABS.map(tab => (
              <button key={tab.key}
                className={`tab ${todoTab===tab.key?"active":""}`}
                onClick={()=>setTodoTab(tab.key)}>
                <Icon n={tab.icon} s={12}/> {tab.label}
                {tab.count > 0 && <span className={`badge-count ${tab.key==="respond-rn" && tab.count > 0 ? "amber" : ""}`}>{tab.count}</span>}
              </button>
            ))}
          </div>
        </div>
        <div className="sec-body flush">
          {items.length === 0 ? (
            <EmptyState icon="check-circle" title="Nothing here — you're caught up"
              sub={
                todoTab==="work-on"   ? "No WPIDs you're preparing right now." :
                todoTab==="respond-rn"? "No Review Notes are waiting on your response." :
                                        "No WPIDs are waiting on your review or sign-off."
              }/>
          ) : items.map(renderTodoRow)}
        </div>
      </div>
    );
  };

  /* Pending approvals (drafts) — every draft awaiting Admin activation.
     There is no explicit "submit" step (Creators only create/edit/save drafts),
     so the time column shows last-updated, not submitted.
     Per row: Project name + entity + risk + creator + Review-&-publish action. */
  const renderPendingDrafts = () => (
    <div className="sec">
      <div className="sec-head">
        <span className="sec-title"><Icon n="inbox" s={14}/> Pending approvals <span className="badge">{pendingDrafts.length}</span></span>
      </div>
      <div className="sec-body flush">
        {pendingDrafts.length === 0 ? (
          <EmptyState icon="sparkle" title="No pending approvals" sub="Drafts submitted by Supervisors and your own drafts will appear here."/>
        ) : (
          <div className="tbl-wrap"><table className="tbl">
            <thead><tr>
              <th style={{width:"32%"}}>Project</th>
              <th>Entity</th>
              <th>Risk</th>
              <th>Creator</th>
              <th>Updated</th>
              <th style={{width:170, textAlign:"right"}}></th>
            </tr></thead>
            <tbody>
              {pendingDrafts.map(p => {
                const e = entityById(p.entityId);
                const u = userById(p.createdBy);
                return (
                  <tr key={p.id} className="clickable" onClick={()=>nav.go({view:"project-draft", projectId:p.id})}>
                    <td>
                      <div style={{display:"flex",flexDirection:"column",gap:3}}>
                        <span style={{fontWeight:600}}>{p.name}</span>
                        <span style={{fontSize:10.5,color:"var(--muted)"}}>{CATEGORY_INFO[p.category]?.label || `Category ${p.category}`}</span>
                      </div>
                    </td>
                    <td>
                      <div style={{display:"flex",alignItems:"center",gap:8}}>
                        <span className="ent-mark" style={{width:24,height:24,fontSize:9,background:"var(--ink)"}}>{e.code}</span>
                        <span className="truncate" style={{maxWidth:160}}>{e.name}</span>
                      </div>
                    </td>
                    <td><RiskBadge level={p.riskLevel}/></td>
                    <td>
                      <div style={{display:"flex",alignItems:"center",gap:6}}>
                        <Avatar id={u.id} name={u.name} size="sm"/>
                        <span style={{fontSize:12}}>{u.name}</span>
                      </div>
                    </td>
                    <td>
                      <span className="mono" style={{fontSize:11.5}}>{fmtTsShort(p.lastEditAt || p.createdAt)}</span>
                    </td>
                    <td style={{textAlign:"right"}}>
                      <button className="btn sm primary" onClick={(ev)=>{ev.stopPropagation();nav.go({view:"project-draft", projectId:p.id});}}>
                        Review &amp; publish <Icon n="chev-r" s={11}/>
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table></div>
        )}
      </div>
    </div>
  );

  /* Pending access requests — compact embed of Approval Center §Access */
  const renderPendingAccess = () => (
    <div className="sec">
      <div className="sec-head">
        <span className="sec-title"><Icon n="lock" s={14}/> Pending access requests <span className="badge">{pendingAccess.length}</span></span>
      </div>
      <div className="sec-body flush">
        {pendingAccess.length === 0 ? (
          <EmptyState icon="sparkle" title="No pending access requests" sub="Users requesting to join a specific project will appear here."/>
        ) : (
          <div className="tbl-wrap"><table className="tbl">
            <thead><tr>
              <th>User</th>
              <th>Requesting to join</th>
              <th>Reason</th>
              <th>Submitted</th>
              <th style={{width:200, textAlign:"right"}}></th>
            </tr></thead>
            <tbody>
              {pendingAccess.map(r => {
                const u = userById(r.userId);
                const p = projectById(r.projectId);
                const e = p ? entityById(p.entityId) : null;
                return (
                  <tr key={r.id}>
                    <td>
                      <div style={{display:"flex",alignItems:"center",gap:8}}>
                        <Avatar id={u.id} name={u.name} size="sm"/>
                        <div>
                          <div style={{fontWeight:500,fontSize:12.5}}>{u.name}</div>
                          <div className="muted mono" style={{fontSize:10.5}}>{u.role}</div>
                        </div>
                      </div>
                    </td>
                    <td>
                      {p ? (
                        <div style={{display:"flex",alignItems:"center",gap:8}}>
                          {e && <span className="ent-mark" style={{width:22,height:22,fontSize:8.5,background:"var(--ink)"}}>{e.code}</span>}
                          <div style={{minWidth:0}}>
                            <div className="truncate" style={{fontWeight:500,fontSize:12.5,maxWidth:170}}>{p.name}</div>
                            {e && <div className="muted" style={{fontSize:11}}>{e.name}</div>}
                          </div>
                        </div>
                      ) : <span className="muted">Unknown project</span>}
                    </td>
                    <td style={{maxWidth:280}}>
                      <span style={{fontSize:12, color: r.reason === "—" ? "var(--muted)" : "var(--ink-2)"}}>
                        {r.reason || "—"}
                      </span>
                    </td>
                    <td>
                      <span className="mono" style={{fontSize:11.5}}>{fmtTsShort(r.requestedAt)}</span>
                    </td>
                    <td style={{textAlign:"right"}}>
                      <div style={{display:"inline-flex",gap:6}}>
                        <button className="btn sm danger" onClick={()=>setDeclineTarget({ req: r })}>
                          <Icon n="x" s={11}/> Decline
                        </button>
                        <button className="btn sm primary" onClick={()=>nav.decideAccess(r.id, "granted")}>
                          <Icon n="check" s={11}/> Grant
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table></div>
        )}
      </div>
    </div>
  );

  const renderEngagements = () => (
    <div className="sec">
      <div className="sec-head">
        <span className="sec-title"><Icon n="layers" s={14}/> My Projects <span className="badge">{myActive.length}</span></span>
        <div className="sec-actions">
          <button className="btn sm ghost" onClick={()=>nav.go({view:"entities"})}>
            All entities <Icon n="arrow-r" s={11}/>
          </button>
        </div>
      </div>
      <div className="sec-body flush">
        {myActive.length === 0 ? (
          <EmptyState icon="folder" title="No active engagements" sub="Approved projects you're a member of will appear here."/>
        ) : (
          <div className="engagement-strip">
            {myActive.map(p => {
              const e    = entityById(p.entityId);
              const days = daysToAutoArchive(p);
              const tone = archiveTone(days);
              return (
                <div key={p.id} className="engagement-chip" onClick={()=>openProject(p.id)}>
                  <span className="ent-mark" style={{width:26,height:26,fontSize:9,background:"var(--ink)"}}>{e.code}</span>
                  <div style={{minWidth:0}}>
                    <div className="e-name truncate">{p.name}</div>
                    <div className="e-meta">{e.name} · {CATEGORY_INFO[p.category]?.label || `Category ${p.category}`}</div>
                  </div>
                  <div className="avatar-stack">
                    {p.members.slice(0,3).map(uid => {
                      const u = userById(uid);
                      return <Avatar key={uid} id={uid} name={u.name} size="sm"/>;
                    })}
                    {p.members.length > 3 && (
                      <span className="avatar sm" style={{background:"var(--ink)",color:"#fff",borderColor:"transparent"}}>+{p.members.length-3}</span>
                    )}
                  </div>
                  {days != null ? (
                    <span className={`sbadge ${tone==="danger"?"danger":tone==="warn"?"warn":""}`} style={{padding:"2px 8px",fontSize:11}}>
                      <Icon n="clock" s={10.5}/> T-{days}d
                    </span>
                  ) : (
                    <button className="btn sm" onClick={(ev)=>{ev.stopPropagation();openProject(p.id);}}>
                      Open <Icon n="chev-r" s={11}/>
                    </button>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );

  /* ---------- Render ---------- */
  return (
    <>
      <div className="page-head">
        <div className="page-title-row">
          <h1 className="page-title">{greeting}, {firstName}</h1>
        </div>
        <div className="page-sub">
          Files you've been working on, things waiting on you, and the projects you're a member of — across every entity.
        </div>
      </div>

      <div className="page-body">
        {renderTodo()}
        {renderRecent()}
        {renderEngagements()}
        {isAdmin && renderPendingDrafts()}
        {isAdmin && renderPendingAccess()}
      </div>

      {declineTarget && (
        <DeclineReasonModal
          count={1}
          requesterName={userById(declineTarget.req.userId)?.name || null}
          projectName={projectById(declineTarget.req.projectId)?.name || declineTarget.req.projectId}
          onClose={()=>setDeclineTarget(null)}
          onConfirm={(reason)=>{
            nav.decideAccess(declineTarget.req.id, "declined", reason);
            setDeclineTarget(null);
          }}/>
      )}
    </>
  );
};

Object.assign(window, { MyWorkspace });
