/* ============================================================
   Lane View — per MTG4 §2.4
   ============================================================
   "เลนของคนทำ" + "เลนของคนตรวจ" — each user sees:
   - My Work — WPIDs I'm preparing + RNs assigned to me
   - My Reviews — WPIDs waiting for my review + RNs I opened
   Built from the same WPID / sign-chain / review-notes data used in the
   project workspace, but pivoted around the current user.
   ============================================================ */

const LaneViewScreen = ({ state, nav }) => {
  const [view, setView] = React.useState("preparer"); // preparer | reviewer
  const [projectFilter, setProjectFilter] = React.useState("all");
  /* POC demo: lets you peek as any user. In production this would be the logged-in user only. */
  const [asUserId, setAsUserId] = React.useState(CURRENT_ADMIN.id);
  const me = userById(asUserId) || CURRENT_ADMIN;

  /* === Demo data: aggregate WPIDs + sign chain + notes across all active projects ===
     POC: we only have one workspace dataset (WPIDS_2200 / SIGN_CHAIN_2202 / REVIEW_NOTES_2202),
     so we pivot it and attach a sample project for demonstration. */
  const wpidsAll = React.useMemo(() => {
    return WPIDS_2200.map(w => ({
      ...w,
      projectId: "P-2025-008",
      projectName: "Annual Audit FY2025",
      entityCode: "NWI",
      folder: "02.2 — Materiality",
    }));
  }, []);

  /* Preparer lane — WPIDs current user owns + RNs assigned to them */
  const myPrepWpids = wpidsAll.filter(w => w.preparedBy === me.id);
  /* For demo, include WPIDs where any reviewer = me */
  const myReviewWpids = wpidsAll.filter(w => {
    const chain = w.id === "2202" ? SIGN_CHAIN_2202 : [];
    return chain.some(c => c.userId === me.id && c.status === "pending");
  });

  const allRNs = REVIEW_NOTES_2202;
  const myRnAssigned = allRNs.filter(n => !n.resolved && n.assigneeId === me.id);
  const myRnOpened   = allRNs.filter(n => !n.resolved && n.userId === me.id);

  /* If logged-in user has no assigned work, show a friendly empty state and
     suggest switching to a different role/user. */
  const isAdmin = me.role === "Admin";

  const cardWp = (w, lane) => {
    const lock = lockInfo(w, me.id);
    const sMeta = WPID_STATUS_META[normalizeWpidStatus(w.status)];
    return (
      <div key={w.id} className="lane-card" onClick={()=>nav.go({view:"project-structure", projectId: w.projectId})}
        style={{
          padding:12, background:"#fff", border:"1px solid var(--line)", borderRadius:"var(--radius)",
          cursor:"pointer", display:"flex", flexDirection:"column", gap:6,
        }}>
        <div style={{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"}}>
          <span className="badge mono" style={{fontSize:9.5,fontWeight:600}}>{w.entityCode}</span>
          <span style={{fontSize:11.5,color:"var(--muted)"}}>{w.projectName}</span>
        </div>
        <div style={{fontWeight:600,fontSize:13,lineHeight:1.35}}>{w.name}</div>
        <div className="mono" style={{fontSize:10.5,color:"var(--muted-2)"}}>.{w.type} · {w.size} · {w.folder}</div>
        <div style={{display:"flex",alignItems:"center",gap:6,marginTop:4,flexWrap:"wrap"}}>
          {sMeta && (
            <span className={`sbadge ${sMeta.tone}`} style={{fontSize:10.5}}>
              <Icon n={sMeta.icon} s={10}/> {sMeta.label}
            </span>
          )}
          {lock.locked && lock.isMe && <span className="sbadge warn" style={{fontSize:10}}><Icon n="lock" s={10}/> You editing</span>}
          {w.v && w.v !== "—" && <span className="mono" style={{fontSize:10,color:"var(--muted)"}}>v {w.v}</span>}
        </div>
      </div>
    );
  };

  const cardRn = (n) => {
    return (
      <div key={n.id} className="lane-card" onClick={()=>nav.go({view:"project-structure", projectId:"P-2025-008"})}
        style={{
          padding:12, background:"#fff", border:"1px solid var(--line)", borderRadius:"var(--radius)",
          borderLeft:"4px solid var(--warn-ink)",
          cursor:"pointer", display:"flex", flexDirection:"column", gap:5,
        }}>
        <div style={{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"}}>
          <Icon n="edit-3" s={11} c="muted"/>
          <span className="mono" style={{fontSize:9.5,color:"var(--muted)"}}>{n.id}</span>
          <span className="mono" style={{fontSize:10,color:"var(--muted-2)"}}>· WP-{n.wpidHistory?.[n.wpidHistory.length-1]?.wpid || "?"}</span>
          <span style={{flex:1}}/>
          <span className="mono" style={{fontSize:10,color:"var(--muted)"}}>{n.ts}</span>
        </div>
        {n.subject && <div style={{fontWeight:600,fontSize:12.5}}>{n.subject}</div>}
        <div style={{fontSize:11.5,color:"var(--ink-2)",lineHeight:1.5,maxHeight:54,overflow:"hidden",textOverflow:"ellipsis"}}>
          {n.text?.replace(/\*\*/g,"").replace(/`/g,"")}
        </div>
        <div style={{display:"flex",alignItems:"center",gap:6,marginTop:2,fontSize:10.5,color:"var(--muted)"}}>
          <Icon n="user" s={10}/>
          <span>from <b>{n.name}</b></span>
          {n.assigneeName && <><span>· →</span><b>{n.assigneeName}</b></>}
          {n.screenshots?.length > 0 && <><span>·</span><span>📷 {n.screenshots.length}</span></>}
        </div>
      </div>
    );
  };

  return (
    <>
      <div className="page-head tight">
        <div className="page-title-row">
          <h1 className="page-title">Lane View</h1>
          <span className="badge mono">เลนคนทำ + เลนคนตรวจ</span>
        </div>
        <div className="page-sub">
          Personal task board — see all the WPIDs and Review Notes assigned to you across every active project, grouped by what you're <b>preparing</b> vs. what you're <b>reviewing</b>.
        </div>
      </div>

      <div className="tabbar">
        <button className={`tab ${view==="preparer"?"active":""}`} onClick={()=>setView("preparer")}>
          <Icon n="pencil" s={13}/> เลนของคนทำ (My Work)
          <span className={`badge-count ${(myPrepWpids.length + myRnAssigned.length)>0?"amber":""}`}>{myPrepWpids.length + myRnAssigned.length}</span>
        </button>
        <button className={`tab ${view==="reviewer"?"active":""}`} onClick={()=>setView("reviewer")}>
          <Icon n="eye" s={13}/> เลนของคนตรวจ (My Reviews)
          <span className={`badge-count ${(myReviewWpids.length + myRnOpened.length)>0?"amber":""}`}>{myReviewWpids.length + myRnOpened.length}</span>
        </button>
      </div>

      <div className="page-body">
        <div style={{display:"flex",alignItems:"center",gap:10,marginBottom:14,flexWrap:"wrap"}}>
          <div style={{display:"flex",alignItems:"center",gap:6}}>
            <span className="mono" style={{fontSize:10.5,color:"var(--muted)",textTransform:"uppercase",letterSpacing:".05em"}}>Viewing as</span>
            <select className="btn sm" value={asUserId} onChange={e=>setAsUserId(e.target.value)} style={{paddingRight:24, minWidth:180}}>
              {USERS.filter(u => u.active !== false).map(u => (
                <option key={u.id} value={u.id}>{u.name} ({u.role})</option>
              ))}
            </select>
            <span className="badge mono" style={{fontSize:10}} title="POC demo only — in production this is locked to the signed-in user">demo</span>
          </div>
          <span style={{flex:1}}/>
          <select className="btn sm" value={projectFilter} onChange={e=>setProjectFilter(e.target.value)} style={{paddingRight:24}}>
            <option value="all">All projects</option>
            {state.projects.filter(p => p.status === "active").map(p => (
              <option key={p.id} value={p.id}>{p.name}</option>
            ))}
          </select>
        </div>

        {view === "preparer" && (
          <div className="lane-grid" style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
            {/* === Column 1: WPIDs I'm preparing === */}
            <div>
              <div className="lane-head" style={{display:"flex",alignItems:"center",gap:8,marginBottom:10}}>
                <Icon n="pencil" s={14} c="muted"/>
                <h3 style={{margin:0,fontSize:14}}>WPIDs I'm preparing</h3>
                <span className="badge">{myPrepWpids.length}</span>
              </div>
              {myPrepWpids.length === 0 ? (
                <div className="card"><EmptyState icon="pencil" title="Nothing assigned yet" sub={`No WPIDs with you as Preparer.${!isAdmin ? "" : " (Try switching CURRENT_ADMIN to a Staff user to see this populated.)"}`}/></div>
              ) : (
                <div style={{display:"flex",flexDirection:"column",gap:10}}>
                  {myPrepWpids.map(w => cardWp(w, "preparer"))}
                </div>
              )}
            </div>

            {/* === Column 2: Review Notes assigned to me === */}
            <div>
              <div className="lane-head" style={{display:"flex",alignItems:"center",gap:8,marginBottom:10}}>
                <Icon n="edit-3" s={14} c="muted"/>
                <h3 style={{margin:0,fontSize:14}}>Review Notes assigned to me</h3>
                <span className="badge warn">{myRnAssigned.length}</span>
              </div>
              {myRnAssigned.length === 0 ? (
                <div className="card"><EmptyState icon="edit-3" title="No open Review Notes" sub="When a reviewer assigns you a Review Note, it appears here."/></div>
              ) : (
                <div style={{display:"flex",flexDirection:"column",gap:10}}>
                  {myRnAssigned.map(n => cardRn(n))}
                </div>
              )}
            </div>
          </div>
        )}

        {view === "reviewer" && (
          <div className="lane-grid" style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
            {/* === Column 1: WPIDs waiting for my review === */}
            <div>
              <div className="lane-head" style={{display:"flex",alignItems:"center",gap:8,marginBottom:10}}>
                <Icon n="eye" s={14} c="muted"/>
                <h3 style={{margin:0,fontSize:14}}>WPIDs waiting for my review</h3>
                <span className="badge warn">{myReviewWpids.length}</span>
              </div>
              {myReviewWpids.length === 0 ? (
                <div className="card"><EmptyState icon="eye" title="Nothing to review" sub="WPIDs where you're a pending sign-off appear here."/></div>
              ) : (
                <div style={{display:"flex",flexDirection:"column",gap:10}}>
                  {myReviewWpids.map(w => cardWp(w, "reviewer"))}
                </div>
              )}
            </div>

            {/* === Column 2: Review Notes I opened (waiting on responses) === */}
            <div>
              <div className="lane-head" style={{display:"flex",alignItems:"center",gap:8,marginBottom:10}}>
                <Icon n="send" s={14} c="muted"/>
                <h3 style={{margin:0,fontSize:14}}>Review Notes I opened</h3>
                <span className="badge">{myRnOpened.length}</span>
              </div>
              {myRnOpened.length === 0 ? (
                <div className="card"><EmptyState icon="send" title="No open Review Notes by you" sub="Notes you opened that are still unresolved appear here."/></div>
              ) : (
                <div style={{display:"flex",flexDirection:"column",gap:10}}>
                  {myRnOpened.map(n => cardRn(n))}
                </div>
              )}
            </div>
          </div>
        )}

        <div className="banner muted" style={{marginTop:14}}>
          <div className="b-ico"><Icon n="info" s={14}/></div>
          <div className="b-body">
            <b>How Lane View works</b> — Every WPID has a Preparer; every Review Note has an Assignee. Lane View pivots these around you so you can see at a glance what's on your plate. Click any card to jump into the project workspace.
          </div>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { LaneViewScreen });
