/* Deal Card — stage stepper, won-block for lead-linked, amount rules, RBAC.
   SoT: monolith-docs/lead-card/deals-tab.md */
const { useState: useStateDC } = React;

function DealCard({ deal, role, onBack, onOpenParent, onConvertLead }) {
  const RB = window.MonolitRBAC;
  const isViewer = role === 'Viewer';
  const isFinal = DEAL_STAGES[deal.stage].final;
  const leadLinked = deal.leadId !== null;
  const readOnly = isViewer;
  const canClose = RB.can(role, 'deals.close') && !isViewer;
  const amountMissingForLate = deal.value == null;
  const overdueClose = dealIsActive(deal) && deal.expectedClose && new Date(deal.expectedClose) < window.MonolitData.NOW;

  const stepperStages = [...ACTIVE_STAGES, 'won'];
  const curIdx = stepperStages.indexOf(deal.stage);

  return (
    <React.Fragment>
      <div className="mn-page-h" style={{ paddingBottom: 0 }}>
        <button className="mn-drawer-back" onClick={onBack} type="button">
          <Icon name="arrow-left" size="xs" /> Back to deals
        </button>
        <div className="mn-page-actions">
          <Button variant="quiet" size="md" icon="copy" title="Copy link">Copy link</Button>
          {!readOnly && !isFinal ? <Button variant="ghost" size="md" icon="more-horizontal">Actions</Button> : null}
          {!readOnly && !isFinal && canClose ? (
            leadLinked ? (
              <Button variant="secondary" size="md" icon="check-check" disabled
                      title="Won is blocked until the lead is converted">Mark won</Button>
            ) : (
              <Button variant="secondary" size="md" icon="check-check"
                      disabled={amountMissingForLate}
                      title={amountMissingForLate ? 'Amount > 0 is required for Won' : undefined}>Mark won</Button>
            )
          ) : null}
        </div>
      </div>

      <div className="mn-leadcard">
        <div className="mn-leadcard-l">
          <header className="mn-lead-header">
            <div className="mn-lead-id-row">
              <span className="mn-lead-id">{deal.id}</span>
              <span className="mn-mono mn-muted" style={{ fontSize: 12 }}>·</span>
              <span className="mn-mono mn-muted" style={{ fontSize: 12 }}>created {new Date(deal.createdAt).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })}</span>
              <span className="mn-mono mn-muted" style={{ fontSize: 12 }}>·</span>
              <span className="mn-mono mn-muted" style={{ fontSize: 12 }}>updated {relTime(new Date(deal.updatedAt))}</span>
              <span className={`mn-chip mn-chip--rel-${leadLinked ? 'lead' : 'client'}`} style={{ marginLeft: 6 }}>
                <Icon name={leadLinked ? 'users' : 'building-2'} size="xs" stroke="2" />{leadLinked ? 'lead-linked' : 'client-linked'}
              </span>
            </div>
            <div className="mn-lead-title-row">
              <div style={{ flex: 1 }}>
                <h1 className="mn-lead-title">{deal.name}</h1>
                <div className="mn-lead-co">
                  <button type="button" className="mn-drawer-back" style={{ padding: 0 }} onClick={onOpenParent}>
                    {deal.parentLabel} <Icon name="arrow-up-right" size="xs" />
                  </button>
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
                <DealStageChip stage={deal.stage} size="lg" onClick={!readOnly && !isFinal ? () => {} : undefined} />
                {fmtMoney(deal)
                  ? <span className="mn-mono" style={{ fontSize: 18, fontWeight: 700 }}>{fmtMoney(deal)}</span>
                  : <span className="mn-chip mn-chip--nonext">No amount yet</span>}
              </div>
            </div>

            <div style={{ padding: '4px 0 2px' }}>
              <div className="mn-stagebar">
                {stepperStages.map((st, i) => {
                  const cfg = DEAL_STAGES[st];
                  const cls = ['mn-stagebar-step'];
                  if (isFinal && deal.stage !== 'won') {
                    if (i <= curIdx) cls.push('mn-stagebar-step--lostlike');
                  } else if (st === 'won' && deal.stage === 'won') cls.push('mn-stagebar-step--won');
                  else if (i < curIdx) cls.push('mn-stagebar-step--done');
                  else if (i === curIdx) cls.push('mn-stagebar-step--current');
                  const wonBlocked = st === 'won' && leadLinked;
                  return (
                    <button key={st} type="button" className={cls.join(' ')}
                            disabled={readOnly || isFinal || wonBlocked}
                            title={wonBlocked ? 'Won is unavailable until the lead is converted' : `Move to ${cfg.label} (${cfg.prob}%)`}>
                      <span className="mn-stagebar-bar"></span>
                      <span className="mn-stagebar-lbl">{cfg.label} · {cfg.prob}%</span>
                    </button>
                  );
                })}
              </div>
              {isFinal && deal.stage !== 'won' ? (
                <div style={{ font: 'var(--font-weight-medium) 12px/16px var(--font-sans)', color: 'var(--text-3)', marginTop: 6 }}>
                  Closed as {DEAL_STAGES[deal.stage].label}{deal.lostReason ? ` — ${deal.lostReason}` : deal.cancelReason ? ` — ${deal.cancelReason}` : ''} · {relTime(new Date(deal.closedAt))}
                </div>
              ) : null}
            </div>

            {leadLinked && !isFinal ? (
              <div className="mn-robanner" style={{ margin: '8px 0 0' }}>
                <Icon name="info" size="sm" />
                Pre-sales deal: Won is blocked until the lead is converted.
                <Button variant="secondary" size="sm" icon="check-check" onClick={onConvertLead}>Convert lead</Button>
              </div>
            ) : null}
            {isViewer ? (
              <div className="mn-robanner" style={{ margin: '8px 0 0' }}>
                <Icon name="eye" size="sm" />Read-only access — your role is Viewer.
              </div>
            ) : null}

            <div className="mn-lead-quick">
              <Button variant="ghost" size="md" icon="plus-square" disabled={readOnly || isFinal || !RB.can(role, 'activities.create')}>Add activity</Button>
              <Button variant="ghost" size="md" icon="paperclip" disabled={readOnly || isFinal}>Attach file</Button>
              {!isFinal && canClose ? (
                <React.Fragment>
                  <Button variant="ghost" size="md" icon="x" title="Requires a lost reason">Mark lost</Button>
                  <Button variant="ghost" size="md" icon="ban" title="Requires a cancel reason">Cancel deal</Button>
                </React.Fragment>
              ) : null}
              <div className="mn-toolbar-spacer" />
              {!readOnly && !isFinal ? <Button variant="quiet" size="md" icon="pencil">Edit details</Button> : null}
            </div>
          </header>

          <div className="mn-stack-lg" style={{ paddingTop: 16 }}>
            {!isFinal && amountMissingForLate ? (
              <Card title="Amount required ahead" eyebrow="Validation rule" padding="md">
                <p style={{ font: 'var(--font-weight-default) 13px/20px var(--font-sans)', color: 'var(--text-2)', margin: 0 }}>
                  Amount is optional on Open / Discovery / Qualification, but becomes <strong>required to enter Proposal, Negotiation or Won</strong>. Add an amount before advancing the stage.
                </p>
              </Card>
            ) : null}

            <Card title="Activity" eyebrow="Linked to this deal"
                  action={!readOnly && !isFinal ? <Button variant="primary" size="sm" icon="plus">Add activity</Button> : null}>
              <div className="mn-feed">
                {window.MonolitData.activity.slice(0, 3).map((a) => <FeedItem key={a.id} a={a} />)}
              </div>
            </Card>

            <Card title="Audit log" eyebrow="Deal lifecycle events">
              <table className="mn-table" style={{ marginTop: -8 }}>
                <thead>
                  <tr><th>Time</th><th>Event</th><th>Detail</th><th>By</th></tr>
                </thead>
                <tbody>
                  {dealAuditRows(deal).map((a, i) => (
                    <tr key={i}>
                      <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{a.at}</span></td>
                      <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-2)' }}>{a.evt}</span></td>
                      <td>{a.detail}</td>
                      <td>{a.who}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>
          </div>
        </div>

        <aside className="mn-leadcard-r">
          <Card title="Details" eyebrow="Deal metadata" padding="md">
            <dl className="mn-kv">
              <dt>Public ID</dt><dd className="mono">{deal.id}</dd>
              <dt>Relationship</dt><dd className="mono">{leadLinked ? 'lead-linked' : 'client-linked'}</dd>
              <dt>{leadLinked ? 'Lead' : 'Client'}</dt><dd className="mono">{leadLinked ? deal.leadId : deal.clientId}</dd>
              <dt>Source</dt><dd className="mono">{deal.source}</dd>
              <dt>Currency</dt><dd>EUR (tenant default)</dd>
            </dl>
          </Card>

          <Card title="Forecast" eyebrow="Stage probability model" padding="md">
            <dl className="mn-kv">
              <dt>Stage</dt><dd>{DEAL_STAGES[deal.stage].label}</dd>
              <dt>Probability</dt><dd className="mono">{DEAL_STAGES[deal.stage].prob}%</dd>
              <dt>Weighted</dt><dd className="mono">{deal.value != null && dealIsActive(deal) ? `€${Math.round(deal.value * DEAL_STAGES[deal.stage].prob / 100).toLocaleString('en-GB')}` : '—'}</dd>
              <dt>Expected close</dt>
              <dd style={{ color: overdueClose ? 'var(--error-main)' : undefined }}>
                {deal.expectedClose ? new Date(deal.expectedClose).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) + (overdueClose ? ' · overdue' : '') : '—'}
              </dd>
            </dl>
            {leadLinked && dealIsActive(deal) ? (
              <div style={{ font: 'var(--font-weight-medium) 11px/15px var(--font-sans)', color: 'var(--text-3)', marginTop: 8, paddingTop: 8, borderTop: '1px dashed var(--border-1)' }}>
                Pre-sales pipeline only — excluded from weighted forecast and closed revenue.
              </div>
            ) : null}
          </Card>

          <Card title="Owner" eyebrow="Deal owner ≠ client owner" padding="md"
                action={RB.can(role, 'deals.assign') && !isFinal ? <Button variant="quiet" size="sm" icon="user-plus" title="Reassign" /> : null}>
            {deal.owner ? (
              <div className="mn-row" style={{ gap: 8 }}>
                <Avatar user={deal.owner} size={28} />
                <div>
                  <div style={{ font: 'var(--font-weight-strong) 13px/18px var(--font-sans)' }}>{deal.owner.name}</div>
                  <div style={{ font: 'var(--font-weight-medium) 11px/14px var(--font-sans)', color: 'var(--text-3)' }}>scope is computed by deal owner</div>
                </div>
              </div>
            ) : (
              <span className="mn-chip mn-chip--noowner"><Icon name="user-x" size="xs" stroke="2" />No owner</span>
            )}
          </Card>

          {RB.can(role, 'deals.delete') ? (
            <Card title="Danger zone" eyebrow="Soft delete · confirmation + 2FA" padding="md">
              <Button variant="destructive" size="md" icon="trash-2" fullWidth>Delete deal</Button>
              <div style={{ font: 'var(--font-weight-medium) 11px/15px var(--font-sans)', color: 'var(--text-3)', marginTop: 8 }}>
                Lost / Cancelled is the normal way to finish a deal — delete is for data correction only.
              </div>
            </Card>
          ) : null}
        </aside>
      </div>
    </React.Fragment>
  );
}

function dealAuditRows(deal) {
  const rows = [];
  if (deal.stage === 'won') rows.push({ who: deal.owner ? deal.owner.name : 'system', at: relTime(new Date(deal.closedAt)), evt: 'deal.marked_won', detail: `confirmed revenue ${fmtMoney(deal)}` });
  if (deal.stage === 'lost') rows.push({ who: deal.owner ? deal.owner.name : 'system', at: relTime(new Date(deal.closedAt)), evt: 'deal.marked_lost', detail: `reason: ${deal.lostReason}` });
  if (deal.stage === 'cancelled') rows.push({ who: deal.owner ? deal.owner.name : 'system', at: relTime(new Date(deal.closedAt)), evt: 'deal.cancelled', detail: `reason: ${deal.cancelReason}` });
  if (dealIsActive(deal) && deal.stage !== 'open') rows.push({ who: deal.owner ? deal.owner.name : 'system', at: relTime(new Date(deal.updatedAt)), evt: 'deal.stage_changed', detail: `→ ${DEAL_STAGES[deal.stage].label}` });
  if (deal.value != null) rows.push({ who: deal.owner ? deal.owner.name : 'system', at: relTime(new Date(deal.updatedAt)), evt: 'deal.amount_changed', detail: `null → ${fmtMoney(deal)}` });
  if (deal.source === 'lead_conversion') rows.push({ who: 'system', at: relTime(new Date(deal.createdAt)), evt: 'deal.relinked_to_client', detail: 'lead-linked → client-linked (conversion batch)' });
  rows.push({ who: deal.owner ? deal.owner.name : 'system', at: relTime(new Date(deal.createdAt)), evt: 'deal.created', detail: `relationship=${deal.leadId ? 'lead-linked' : 'client-linked'}` });
  return rows;
}

Object.assign(window, { DealCard });
