// -----------------------------------------------------------------
// Mission Drawer — a right-side panel for a single Mission.
//
// Opens when a mission card is clicked. Not a modal — no route change.
// For heavier work the "Open full workspace" link (footer) would
// eventually deep-link to a dedicated mission page (future phase).
// -----------------------------------------------------------------

function MissionDrawer({ mission, onClose, missionsRef, pdata, stageN }) {
  const [tab, setTab] = React.useState('checklist');
  const meta = (missionsRef || window.MYGENI_MISSIONS)[mission.key] || {};
  const tone = (window.MYGENI_MISSION_TONES || {})[meta.tone] || (window.MYGENI_MISSION_TONES || {}).blue;
  const statusMeta = (window.MYGENI_MISSION_STATUS || {})[mission.status] || { label: mission.status, tone: 'gray' };

  // Phase 12 — derive linked canonical items from pdata via the helpers
  // (mission-model.js). Never inline these into the mission.
  const linked = React.useMemo(() => {
    if (!pdata) return { research: [], designScreens: [], designFlows: [], dev: [], docs: [], commercial: [] };
    const research      = window.linkedResearch?.(pdata, mission.key, stageN) || [];
    const design        = window.linkedDesign?.(pdata, mission.key, stageN)   || { screens: [], flows: [] };
    const dev           = window.linkedDev?.(pdata, mission.key, stageN)      || [];
    const docs          = window.linkedDocuments?.(pdata, mission.key, stageN)|| [];
    const commercial    = window.linkedCommercial?.(pdata, stageN)            || [];
    return {
      research,
      designScreens: design.screens,
      designFlows:   design.flows,
      dev,
      docs,
      commercial,
    };
  }, [pdata, mission.key, stageN]);

  const linkedTotal = linked.research.length + linked.designScreens.length +
                      linked.designFlows.length + linked.dev.length + linked.docs.length +
                      linked.commercial.length;

  // Handle escape close
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  // lock body scroll while open
  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, []);

  const checklist    = mission.checklist    || [];
  const deliverables = mission.deliverables || [];
  const attachments  = mission.attachments  || [];
  const notes        = mission.notes        || '';
  const commercial   = mission.commercial   || null;

  const tabs = [
    { key: 'checklist',    label: 'Checklist',    count: checklist.length },
    { key: 'deliverables', label: 'Deliverables', count: deliverables.length },
    ...(linkedTotal > 0 ? [{ key: 'linked', label: 'Linked', count: linkedTotal }] : []),
    { key: 'attachments',  label: 'Attachments',  count: attachments.length },
    { key: 'notes',        label: 'Notes',        count: notes ? 1 : 0 },
    ...(commercial || (linked.commercial && linked.commercial.length > 0) ? [{ key: 'commercial', label: 'Commercial', count: (commercial ? 1 : 0) + (linked.commercial?.length || 0) }] : []),
  ];

  return (
    <>
      <div className="mission-drawer-backdrop" onClick={onClose} />
      <aside className="mission-drawer" role="dialog" aria-label={`Mission: ${meta.label || mission.title}`}>
        {/* HEAD */}
        <div className="mission-drawer-head">
          <div className="mission-icon" style={{ background: tone.bg, color: tone.fg }}>
            <Icon name={meta.icon || 'features'} size={20} strokeWidth={1.75} />
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
              <div className="title">{mission.title || meta.label}</div>
              <Label tone={statusMeta.tone} dot size="sm">{statusMeta.label}</Label>
            </div>
            <div className="subt">{mission.purpose || meta.purpose}</div>
          </div>
          <button className="close-btn" onClick={onClose} aria-label="Close mission panel">
            <Icon name="x" size={16} strokeWidth={2} />
          </button>
        </div>

        {/* META */}
        <div className="mission-drawer-meta">
          <div className="grow">
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
              <span className="owner">
                Owner <b style={{ color: 'var(--text-primary)' }}>{mission.owner}</b>
                {mission.team && mission.team.length > 0 && <> · {mission.team.length + 1} people</>}
              </span>
              <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-primary)' }}>{mission.progress}%</span>
            </div>
            <div className="p-bar">
              <div className="p-fill" style={{ width: `${mission.progress}%`, background: tone.fg }} />
            </div>
          </div>
          {mission.team && mission.team.length > 0 && <AvatarStack names={[mission.owner, ...mission.team]} max={3} size="sm" />}
        </div>

        {/* TABS */}
        <div className="mission-drawer-tabs">
          {tabs.map(t => (
            <button
              key={t.key}
              className={`mission-drawer-tab${tab === t.key ? ' active' : ''}`}
              onClick={() => setTab(t.key)}
              type="button"
            >
              {t.label}
              {t.count > 0 && <span className="n">{t.count}</span>}
            </button>
          ))}
        </div>

        {/* BODY */}
        <div className="mission-drawer-body">
          {tab === 'checklist' && checklist.length === 0 && (
            <div style={{ fontSize: 13, color: 'var(--text-tertiary)', textAlign: 'center', padding: '20px 0' }}>
              No checklist items yet.
            </div>
          )}
          {tab === 'checklist' && checklist.map((c, i) => (
            <div key={i} className={`md-check ${c.done ? 'done' : 'pending'}`}>
              <div className="mark">
                {c.done && <Icon name="check" size={11} strokeWidth={3} />}
              </div>
              <div>
                <div className="txt">
                  {c.text}
                  {c.required && <span className="req-star" title="Required for stage completion">●</span>}
                </div>
                {c.note && <span className="note">{c.note}</span>}
              </div>
              <div className="meta">
                {c.attachment && (
                  <span className="attach">
                    <Icon name={c.attachment.kind === 'link' ? 'externalLink' : 'paperclip'} size={10} strokeWidth={1.75} />
                    {c.attachment.name}
                  </span>
                )}
                {c.due && <span>{c.due}</span>}
                {c.owner && <Avatar name={c.owner} size="xs" />}
              </div>
            </div>
          ))}

          {tab === 'deliverables' && deliverables.length === 0 && (
            <div style={{ fontSize: 13, color: 'var(--text-tertiary)', textAlign: 'center', padding: '20px 0' }}>
              No deliverables yet.
            </div>
          )}
          {tab === 'deliverables' && deliverables.map((d, i) => (
            <div key={i} className="md-deliv">
              <div className="prev">
                <Icon name={d.previewKind === 'image' ? 'image' : d.previewKind === 'contract' ? 'contracts' : d.previewKind === 'diagram' ? 'stack' : 'fileText'} size={20} strokeWidth={1.5} />
              </div>
              <div style={{ minWidth: 0 }}>
                <div className="n">{d.name}</div>
                <div className="m">
                  <span>{d.type}</span>
                  {d.due && <>·<span>Due {d.due}</span></>}
                  {d.required && <span style={{ color: 'var(--danger-solid)' }}>·<span> Required</span></span>}
                </div>
              </div>
              <div>
                <Label tone={
                  d.status === 'done' ? 'green' :
                  d.status === 'approved' ? 'green' :
                  d.status === 'review' ? 'blue' :
                  d.status === 'blocked' ? 'red' : 'gray'
                } dot size="sm">
                  {d.status.replace(/^./, s => s.toUpperCase())}
                </Label>
              </div>
            </div>
          ))}

          {/* Phase 12 — Linked canonical items */}
          {tab === 'linked' && (
            <>
              {linked.research.length > 0 && (
                <div className="md-linked-group">
                  <div className="md-linked-head">
                    <span>Research</span>
                    <a href={`#/projects/${pdata.id}/research`} onClick={onClose} className="md-linked-open">Open Research →</a>
                  </div>
                  {linked.research.map((r) => (
                    <a href={`#/projects/${pdata.id}/research`} onClick={onClose} className="md-linked-row" key={r.id}>
                      <div className="md-linked-icon"><Icon name="flask" size={13} strokeWidth={1.75}/></div>
                      <div className="md-linked-body">
                        <div className="md-linked-title">{r.title}</div>
                        <div className="md-linked-sub">
                          <span>{r.type}</span><span>·</span><span>{r.by}</span><span>·</span><span>{r.date}</span>
                          {r.links?.required && <span className="md-linked-req">required</span>}
                        </div>
                      </div>
                      {r.links?.state && (
                        <Label
                          tone={r.links.state === 'done' ? 'green' : r.links.state === 'in-progress' ? 'blue' : r.links.state === 'blocked' ? 'red' : 'gray'}
                          dot size="sm"
                        >
                          {r.links.state.replace(/^./, s => s.toUpperCase()).replace('-', ' ')}
                        </Label>
                      )}
                    </a>
                  ))}
                </div>
              )}

              {linked.designScreens.length + linked.designFlows.length > 0 && (
                <div className="md-linked-group">
                  <div className="md-linked-head">
                    <span>Design</span>
                    <a href={`#/projects/${pdata.id}/design`} onClick={onClose} className="md-linked-open">Open Design →</a>
                  </div>
                  {linked.designScreens.map((s) => (
                    <a href={`#/projects/${pdata.id}/design`} onClick={onClose} className="md-linked-row" key={s.id}>
                      <div className="md-linked-icon"><Icon name="palette" size={13} strokeWidth={1.75}/></div>
                      <div className="md-linked-body">
                        <div className="md-linked-title">{s.title}</div>
                        <div className="md-linked-sub">
                          <span>Screen</span><span>·</span><span>{s.stage}</span>
                          {s.links?.required && <span className="md-linked-req">required</span>}
                        </div>
                      </div>
                      {s.links?.state && (
                        <Label
                          tone={s.links.state === 'approved' ? 'green' : s.links.state === 'in-review' ? 'blue' : s.links.state === 'blocked' ? 'red' : 'gray'}
                          dot size="sm"
                        >
                          {s.links.state.replace(/^./, x => x.toUpperCase()).replace('-', ' ')}
                        </Label>
                      )}
                    </a>
                  ))}
                  {linked.designFlows.map((f) => (
                    <a href={`#/projects/${pdata.id}/design`} onClick={onClose} className="md-linked-row" key={f.id}>
                      <div className="md-linked-icon"><Icon name="route" size={13} strokeWidth={1.75}/></div>
                      <div className="md-linked-body">
                        <div className="md-linked-title">{f.title}</div>
                        <div className="md-linked-sub">
                          <span>Flow</span><span>·</span><span>{f.steps} steps</span><span>·</span><span>updated {f.updated}</span>
                        </div>
                      </div>
                      {f.links?.state && (
                        <Label tone={f.links.state === 'approved' ? 'green' : 'blue'} dot size="sm">
                          {f.links.state.replace(/^./, x => x.toUpperCase()).replace('-', ' ')}
                        </Label>
                      )}
                    </a>
                  ))}
                </div>
              )}

              {linked.dev.length > 0 && (
                <div className="md-linked-group">
                  <div className="md-linked-head">
                    <span>Development</span>
                    <a href={`#/projects/${pdata.id}/development`} onClick={onClose} className="md-linked-open">Open Development →</a>
                  </div>
                  {linked.dev.map((d, i) => (
                    <a href={`#/projects/${pdata.id}/development`} onClick={onClose} className="md-linked-row" key={i}>
                      <div className="md-linked-icon"><Icon name="gears" size={13} strokeWidth={1.75}/></div>
                      <div className="md-linked-body">
                        <div className="md-linked-title">{d.name}</div>
                        <div className="md-linked-sub"><span>{d.kind}</span><span>·</span><span>{d.owner}</span></div>
                      </div>
                      {d.links?.state && (
                        <Label
                          tone={d.links.state === 'ready' ? 'green' : d.links.state === 'in-progress' ? 'blue' : d.links.state === 'blocked' ? 'red' : 'gray'}
                          dot size="sm"
                        >
                          {d.links.state.replace(/^./, x => x.toUpperCase()).replace('-', ' ')}
                        </Label>
                      )}
                    </a>
                  ))}
                </div>
              )}

              {linked.docs.length > 0 && (
                <div className="md-linked-group">
                  <div className="md-linked-head">
                    <span>Documents</span>
                    <a href={`#/projects/${pdata.id}/documents`} onClick={onClose} className="md-linked-open">Open Documents →</a>
                  </div>
                  {linked.docs.map((doc) => (
                    <a href={`#/projects/${pdata.id}/documents`} onClick={onClose} className="md-linked-row" key={doc.id}>
                      <div className="md-linked-icon"><Icon name="fileText" size={13} strokeWidth={1.75}/></div>
                      <div className="md-linked-body">
                        <div className="md-linked-title">{doc.title}</div>
                        <div className="md-linked-sub">
                          <span>{doc.kind}</span><span>·</span><span>{doc.size}</span><span>·</span><span>updated {doc.updated}</span>
                        </div>
                      </div>
                    </a>
                  ))}
                </div>
              )}

              {linkedTotal === 0 && (
                <div style={{ fontSize: 13, color: 'var(--text-tertiary)', textAlign: 'center', padding: '24px 0' }}>
                  Nothing linked to this mission yet. Link research, design, or development items from their sections and they will appear here.
                </div>
              )}
            </>
          )}

          {tab === 'attachments' && attachments.length === 0 && (
            <div style={{ fontSize: 13, color: 'var(--text-tertiary)', textAlign: 'center', padding: '20px 0' }}>
              No attachments yet.
            </div>
          )}
          {tab === 'attachments' && (
            <div className="md-att-grid">
              {attachments.map((a, i) => (
                <div key={i} className="md-att">
                  <div className="g">
                    <Icon name={a.kind === 'image' ? 'image' : a.kind === 'link' ? 'externalLink' : a.kind === 'pdf' ? 'fileText' : a.kind === 'contract' ? 'contracts' : 'paperclip'} size={15} strokeWidth={1.75} />
                  </div>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div className="n">{a.name}</div>
                    <div className="m">{a.kind}{a.size ? ` · ${a.size}` : ''}</div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {tab === 'notes' && !notes && (
            <div style={{ fontSize: 13, color: 'var(--text-tertiary)', textAlign: 'center', padding: '20px 0' }}>
              No notes yet.
            </div>
          )}
          {tab === 'notes' && notes && (
            <div style={{ fontSize: 13.5, letterSpacing: '-0.015em', color: 'var(--text-primary)', lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>
              {notes}
            </div>
          )}

          {tab === 'commercial' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {/* Legacy inline commercial context on the mission */}
              {commercial && (
                <>
                  <div style={{ padding: 12, borderRadius: 12, background: 'var(--bg-app)' }}>
                    <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, color: 'var(--text-tertiary)' }}>Related</div>
                    <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: '-0.015em', color: 'var(--text-primary)', marginTop: 3 }}>{commercial.title}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-tertiary)', letterSpacing: '-0.02em', marginTop: 2 }}>{commercial.subtitle}</div>
                  </div>
                  {commercial.items && commercial.items.map((it, i) => (
                    <div key={i} style={{ padding: 10, borderRadius: 10, background: 'var(--bg-app)', display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, alignItems: 'center' }}>
                      <div>
                        <div style={{ fontSize: 12.5, color: 'var(--text-primary)', fontWeight: 600 }}>{it.label}</div>
                        <div style={{ fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '-0.02em', marginTop: 2 }}>{it.note}</div>
                      </div>
                      <div className="mono" style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--text-primary)' }}>{it.value}</div>
                    </div>
                  ))}
                </>
              )}

              {/* Phase 12 — Canonical contract stage-links from the
                  project's contracts. Never a copy of the contract. */}
              {linked.commercial && linked.commercial.length > 0 && linked.commercial.map((cl, i) => (
                <a
                  key={`cl-${i}`}
                  href={`#/projects/${pdata.id}/commercial`}
                  onClick={onClose}
                  style={{ padding: 10, borderRadius: 10, background: 'var(--bg-app)', display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, alignItems: 'center' }}
                >
                  <div>
                    <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, color: 'var(--text-tertiary)' }}>
                      {cl.stageLink.kind === 'payment' ? 'Milestone payment' : cl.stageLink.kind === 'sign-off' ? 'Approval' : cl.stageLink.kind === 'renewal' ? 'Renewal' : 'Contract'}
                    </div>
                    <div style={{ fontSize: 13, color: 'var(--text-primary)', fontWeight: 600, marginTop: 3 }}>{cl.stageLink.label}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '-0.02em', marginTop: 2 }}>{cl.contract.title}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    {cl.stageLink.amount && <div className="mono" style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--text-primary)' }}>{cl.stageLink.amount}</div>}
                    <div style={{ fontSize: 10.5, color: 'var(--text-tertiary)', letterSpacing: '-0.02em', marginTop: 2 }}>{cl.stageLink.date}</div>
                  </div>
                </a>
              ))}

              {!commercial && (!linked.commercial || linked.commercial.length === 0) && (
                <div style={{ fontSize: 13, color: 'var(--text-tertiary)', textAlign: 'center', padding: '20px 0' }}>
                  No commercial context for this mission.
                </div>
              )}
            </div>
          )}
        </div>

        {/* FOOT */}
        <div className="mission-drawer-foot">
          <div style={{ fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '-0.02em' }}>Press <span className="mono" style={{ fontSize: 10, padding: '1px 5px', background: 'var(--bg-app)', borderRadius: 4 }}>Esc</span> to close</div>
          <a className="open-full">
            <span>Open full workspace</span>
            <Icon name="arrowUpRight" size={12} strokeWidth={2} />
          </a>
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { MissionDrawer });
