/* ============================================================================
   FOUNDRY CONTROL — DESKTOP CONSOLE
   Same data + model as the mobile PWA, laid out as a desktop command console:
   tabbed master-detail, requests table, persistent permission inbox, and
   modal dialogs for production publish + agent-authorization requests.
   Shares atoms with the mobile build via window globals.
   ========================================================================== */
function FctlDesktop(p) {
  const W = window;
  const { FChip, ChannelTag, Detail, NewRequest, Deploys, SettingsF, PermissionCard, confirmMeta, fctlStats } = W;
  const cm = p.confirm ? confirmMeta(p.confirm.kind) : {};
  const stats = fctlStats(p.reqs);
  const tab = p.tab === "new" ? "hq" : p.tab;     // desktop has no "new" tab; it's a modal
  const permObj = p.perms.find(x => x.id === p.permSel);

  const TABS = [["hq", "HQ", "globe"], ["inspect", "Inspect", "device"], ["reviews", "Reviews", "eye"], ["deploys", "Deploys", "rocket"], ["settings", "Settings", "settings"]];
  const listForTab = tab === "reviews"
    ? p.reqs.filter(r => ["Preview Live", "Awaiting Approval", "Patch Ready"].includes(r.status))
    : p.reqs;

  function Table({ rows }) {
    return (
      <table className="fctld-table">
        <thead><tr><th>Request</th><th>Type</th><th>Source</th><th>Updated</th><th className="r">Status</th></tr></thead>
        <tbody>
          {rows.map(r => (
            <tr key={r.id} className={"fctld-tr" + (p.sel === r.id ? " on" : "")} onClick={() => p.open(r.id)}>
              <td><div className="fctld-tcell"><span className="fctld-tid">{r.id}</span><span className="fctld-ttitle">{r.title}</span></div></td>
              <td><span className="fctld-ttype">{r.type}</span></td>
              <td><ChannelTag ch={r.channel} cmd={r.cmd} /></td>
              <td><span className="fctld-tupd">{r.created}</span></td>
              <td className="r"><FChip status={r.status} sm /></td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }

  return (
    <div className="fctld">
      {/* tab bar + actions */}
      <div className="fctld-bar">
        <window.ProjectSwitcher project={p.project} reqs={p.allReqs} onPick={p.pickProject} onAll={() => p.pickProject(null)} />
        <div className="fctld-tabs">
          {TABS.map(([id, lbl, ic]) => (
            <button key={id} className={"fctld-tab" + (tab === id ? " on" : "")} onClick={() => p.go(id)}>
              <Icon name={ic} className="glyph" style={{ width: 15, height: 15 }} />{lbl}
            </button>
          ))}
        </div>
        <div className="fctld-baract">
          {p.perms.length > 0 && (
            <button className="fctld-permbtn" onClick={() => { p.back(); p.openPerm(p.perms[0].id); }}>
              <Icon name="shield" className="glyph" style={{ width: 14, height: 14 }} />{p.perms.length} authorization{p.perms.length > 1 ? "s" : ""}
            </button>
          )}
          <button className="btn primary" onClick={() => p.setNewOpen(true)}><Icon name="plus" className="glyph" style={{ width: 15, height: 15 }} /> New request</button>
        </div>
      </div>

      {/* stat strip (HQ) */}
      {tab === "hq" && (
        <div className="fctld-stats">
          {stats.map(c => (
            <button key={c.k} className="fctld-stat focusable" onClick={() => c.k === "Ready to review" && p.go("reviews")}>
              <div className="fctld-stat-top"><Icon name={c.icon} className="glyph" style={{ width: 15, height: 15, color: DW.STATE_META[c.s].c }} /><Led state={c.s} size={7} /></div>
              <div className="fctld-stat-v" style={{ color: DW.STATE_META[c.s].c }}>{c.v}</div>
              <div className="fctld-stat-k">{c.k}</div>
            </button>
          ))}
        </div>
      )}

      {/* master / detail */}
      {tab === "inspect" && <div className="fctld-inspectwrap"><window.InspectProject project={p.project} onCreateCR={p.createCR} /></div>}
      {tab !== "inspect" && (
      <div className="fctld-split">
        <div className="fctld-main comms-scroll">
          {(tab === "hq" || tab === "reviews") && (
            <div className="panel fctld-panel">
              <div className="phead"><span className="eyebrow">{tab === "reviews" ? "Awaiting your review" : "All change requests"}</span><span className="fctld-count">{listForTab.length}</span></div>
              {listForTab.length === 0
                ? <div className="fctld-empty"><Icon name="check" className="glyph" style={{ width: 20, height: 20 }} />Nothing waiting — all clear.</div>
                : <Table rows={listForTab} />}
            </div>
          )}
          {tab === "deploys" && <div className="panel fctld-panel pad"><Deploys open={p.open} /></div>}
          {tab === "settings" && <div className="panel fctld-panel pad"><SettingsF /></div>}
        </div>

        {/* side: detail OR permission inbox OR placeholder */}
        <div className="fctld-side">
          {p.sel && p.selReq ? (
            <div className="panel fctld-detailwrap"><Detail r={p.selReq} back={p.back} act={p.act} /></div>
          ) : p.perms.length > 0 ? (
            <div className="panel fctld-inbox comms-scroll">
              <div className="phead"><span className="eyebrow"><Icon name="shield" className="glyph" style={{ width: 13, height: 13 }} /> Pending authorizations</span><span className="fctld-count gold">{p.perms.length}</span></div>
              <div className="fctld-inbox-body">
                <p className="fctld-inbox-note">Agents act inside fixed authority. These asks need a human decision before the agent may proceed.</p>
                {p.perms.map(pm => <PermissionCard key={pm.id} perm={pm} onResolve={p.resolvePerm} />)}
              </div>
            </div>
          ) : (
            <div className="panel fctld-placeholder">
              <span className="fctld-ph-ring"><Icon name="eye" className="glyph" style={{ width: 22, height: 22 }} /></span>
              <b>Select a request</b>
              <em>Pick a change request to review its diff, validation logs, evidence and deploy controls.</em>
            </div>
          )}
        </div>
      </div>
      )}

      {/* ---- modals ---- */}
      {p.newOpen && (
        <div className="fctld-modal-root">
          <div className="fctld-modal-bd" onClick={() => p.setNewOpen(false)} />
          <div className="fctld-modal">
            <button className="fctld-modal-x focusable" onClick={() => p.setNewOpen(false)}><Icon name="close" className="glyph" style={{ width: 16, height: 16 }} /></button>
            <div className="comms-scroll fctld-modal-body"><NewRequest onSubmit={p.submit} seed={p.seed} project={p.project} /></div>
          </div>
        </div>
      )}

      {permObj && (
        <div className="fctld-modal-root">
          <div className="fctld-modal-bd" onClick={() => p.setPermSel(null)} />
          <div className="fctld-modal narrow"><PermissionCard perm={permObj} onResolve={p.resolvePerm} /></div>
        </div>
      )}

      {p.confirm && (
        <div className="fctld-modal-root">
          <div className="fctld-modal-bd" onClick={() => p.setConfirm(null)} />
          <div className="fctld-confirm">
            <div className={"fctl-sheet-ic " + cm.cls}><Icon name={cm.icon} className="glyph" style={{ width: 20, height: 20 }} /></div>
            <div className="fctl-sheet-t">{cm.t}</div>
            <div className="fctl-sheet-d">{cm.d}</div>
            <div className="fctl-sheet-act">
              <button className="btn ghost" onClick={() => p.setConfirm(null)}>Cancel</button>
              <button className={"btn " + cm.cls} onClick={() => p.applyAct(p.confirm.id, p.confirm.kind)}>{cm.btn}</button>
            </div>
          </div>
        </div>
      )}

      {p.toast && <div className="fctl-toast fctld-toast"><Led state="clear" size={6} />{p.toast}</div>}
    </div>
  );
}

window.FctlDesktop = FctlDesktop;
