/* Deals — global list: pipeline summary, presets, pre-sales vs client-linked.
   SoT: monolith-docs/lead-card/deals-tab.md · client view: client-card/deals-tab.md */
const { useState: useStateDL, useMemo: useMemoDL } = React;

const DEAL_STAGES = {
  open:          { label: 'Open',          prob: 10,  final: false },
  discovery:     { label: 'Discovery',     prob: 20,  final: false },
  qualification: { label: 'Qualification', prob: 30,  final: false },
  proposal:      { label: 'Proposal',      prob: 60,  final: false },
  negotiation:   { label: 'Negotiation',   prob: 80,  final: false },
  won:           { label: 'Won',           prob: 100, final: true },
  lost:          { label: 'Lost',          prob: 0,   final: true },
  cancelled:     { label: 'Cancelled',     prob: 0,   final: true },
};
const ACTIVE_STAGES = ['open', 'discovery', 'qualification', 'proposal', 'negotiation'];

function DealStageChip({ stage, size = 'md', onClick }) {
  const s = DEAL_STAGES[stage] || DEAL_STAGES.open;
  const cls = ['mn-chip', `mn-chip--${size}`, `mn-chip--dl-${stage}`];
  if (onClick) cls.push('mn-chip--btn');
  const icon = stage === 'won' ? 'check-check' : stage === 'lost' ? 'x' : stage === 'cancelled' ? 'ban' : 'circle';
  return (
    <span className={cls.join(' ')} onClick={onClick}>
      <Icon name={icon} size="xs" stroke="2" /> {s.label}
      {onClick ? <Icon name="chevron-down" size="xs" stroke="2" /> : null}
    </span>
  );
}
function dealIsActive(d) { return ACTIVE_STAGES.includes(d.stage); }
function fmtMoney(d) { return d.value != null ? `${d.currency}${d.value.toLocaleString('en-GB')}` : null; }
function scopeDeals(role, list) {
  const RB = window.MonolitRBAC;
  if (role === 'Sales Rep') return list.filter(d => d.owner && d.owner.id === RB.ME);
  if (role === 'Manager')   return list.filter(d => !d.owner || RB.TEAM_IDS.includes(d.owner.id));
  return list;
}

function DealsList({ deals, role, onOpenDeal, onCreate }) {
  const RB = window.MonolitRBAC;
  const scoped = useMemoDL(() => scopeDeals(role, deals), [deals, role]);
  const [preset, setPreset] = useStateDL('active');
  const [query, setQuery] = useStateDL('');
  const isViewer = role === 'Viewer';

  const presets = [
    { id: 'active',    label: 'Active',     filter: d => dealIsActive(d) },
    { id: 'my',        label: 'My deals',   filter: d => dealIsActive(d) && d.owner && d.owner.id === RB.ME },
    { id: 'presales',  label: 'Pre-sales',  filter: d => d.leadId !== null && dealIsActive(d) },
    { id: 'overdue',   label: 'Overdue close', filter: d => dealIsActive(d) && d.expectedClose && new Date(d.expectedClose) < window.MonolitData.NOW },
    { id: 'won',       label: 'Won',        filter: d => d.stage === 'won' },
    { id: 'lost',      label: 'Lost',       filter: d => d.stage === 'lost' },
    { id: 'cancelled', label: 'Cancelled',  filter: d => d.stage === 'cancelled' },
    { id: 'all',       label: 'All',        filter: () => true },
  ];

  const filtered = useMemoDL(() => {
    let r = scoped;
    const p = presets.find(p => p.id === preset);
    if (p) r = r.filter(p.filter);
    if (query) {
      const q = query.toLowerCase();
      r = r.filter(d => (d.id + d.name + d.parentLabel).toLowerCase().includes(q));
    }
    return r.slice().sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt));
  }, [scoped, preset, query]);

  // Pipeline summary — client-linked vs pre-sales kept separate (forecast rule)
  const open = scoped.filter(dealIsActive);
  const clientOpen = open.filter(d => d.clientId);
  const presales = open.filter(d => d.leadId);
  const pipeline = clientOpen.reduce((s, d) => s + (d.value || 0), 0);
  const weighted = clientOpen.reduce((s, d) => s + (d.value || 0) * DEAL_STAGES[d.stage].prob / 100, 0);
  const presalesSum = presales.reduce((s, d) => s + (d.value || 0), 0);

  const presetCount = (p) => scoped.filter(p.filter).length;

  return (
    <React.Fragment>
      <div className="mn-page-h">
        <div className="mn-page-title">
          <h1 className="title-1">Deals</h1>
          <span className="mn-page-count">{filtered.length} of {scoped.length}</span>
        </div>
        <div className="mn-page-actions">
          <Button variant="ghost" size="md" icon="download">Export</Button>
          {RB.can(role, 'deals.create') ? <Button variant="primary" size="md" icon="plus" onClick={onCreate}>New deal</Button> : null}
        </div>
      </div>

      {isViewer ? <div className="mn-robanner"><Icon name="eye" size="sm" />Read-only access — your role is Viewer.</div> : null}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 12, maxWidth: 780, padding: '4px 0 12px' }}>
        <section className="mn-card mn-card--p-md">
          <div className="mn-eyebrow">Open pipeline</div>
          <div className="mn-mono" style={{ fontSize: 20, fontWeight: 700, whiteSpace: 'nowrap' }}>€{(pipeline / 1000).toFixed(0)}k</div>
          <div style={{ font: 'var(--font-weight-medium) 11px/14px var(--font-sans)', color: 'var(--text-3)' }}>{clientOpen.length} client-linked deals</div>
        </section>
        <section className="mn-card mn-card--p-md">
          <div className="mn-eyebrow">Weighted forecast</div>
          <div className="mn-mono" style={{ fontSize: 20, fontWeight: 700, whiteSpace: 'nowrap' }}>€{(weighted / 1000).toFixed(0)}k</div>
          <div style={{ font: 'var(--font-weight-medium) 11px/14px var(--font-sans)', color: 'var(--text-3)' }}>by stage probability</div>
        </section>
        <section className="mn-card mn-card--p-md">
          <div className="mn-eyebrow">Pre-sales pipeline</div>
          <div className="mn-mono" style={{ fontSize: 20, fontWeight: 700, whiteSpace: 'nowrap' }}>€{(presalesSum / 1000).toFixed(0)}k</div>
          <div style={{ font: 'var(--font-weight-medium) 11px/14px var(--font-sans)', color: 'var(--text-3)' }}>{presales.length} lead-linked · excluded from forecast</div>
        </section>
      </div>

      <div className="mn-presets">
        {presets.map((p) => (
          <button key={p.id} type="button"
                  className={'mn-preset' + (preset === p.id ? ' mn-preset--active' : '')}
                  onClick={() => setPreset(p.id)}>
            <span>{p.label}</span>
            <span className="mn-preset-c">{presetCount(p)}</span>
          </button>
        ))}
      </div>

      <div className="mn-toolbar">
        <div style={{ width: 320 }}>
          <Input fullWidth icon="search" placeholder="Search deals…" value={query} onChange={setQuery} />
        </div>
        <Button variant="ghost" size="md" icon="user">Owner</Button>
        <Button variant="ghost" size="md" icon="git-commit-horizontal">Stage</Button>
        <Button variant="ghost" size="md" icon="calendar">Close date</Button>
      </div>

      <div className="mn-table-wrap">
        <table className="mn-table">
          <thead>
            <tr>
              <th style={{ width: 110 }}>ID</th>
              <th>Deal</th>
              <th style={{ width: 140 }}>Stage</th>
              <th style={{ width: 120 }}>Amount</th>
              <th style={{ width: 80 }}>Prob.</th>
              <th style={{ width: 170 }}>Owner</th>
              <th style={{ width: 130 }}>Expected close</th>
              <th style={{ width: 110 }}>Relationship</th>
              <th style={{ width: 100 }}>Updated</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((d) => {
              const overdueClose = dealIsActive(d) && d.expectedClose && new Date(d.expectedClose) < window.MonolitData.NOW;
              return (
                <tr key={d.id} className="mn-row--clickable" onClick={(e) => {
                  if (e.target.closest('button, .mn-chip--btn')) return;
                  onOpenDeal(d.id);
                }}>
                  <td className="mn-cell-id">{d.id}</td>
                  <td>
                    <div className="mn-cell-name-text">
                      <strong>{d.name}</strong>
                      <span>{d.parentLabel}</span>
                    </div>
                  </td>
                  <td><DealStageChip stage={d.stage} /></td>
                  <td>
                    {fmtMoney(d)
                      ? <span className="mn-mono" style={{ fontSize: 13 }}>{fmtMoney(d)}</span>
                      : <span className="mn-chip mn-chip--nonext">No amount</span>}
                  </td>
                  <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{DEAL_STAGES[d.stage].prob}%</span></td>
                  <td>
                    {d.owner
                      ? <div className="mn-cell-owner"><Avatar user={d.owner} size={22} /><span>{d.owner.name}</span></div>
                      : <span className="mn-chip mn-chip--noowner"><Icon name="user-x" size="xs" stroke="2" />No owner</span>}
                  </td>
                  <td style={{ whiteSpace: 'nowrap' }}>
                    {d.expectedClose ? (
                      <span className="mn-mono" style={{ fontSize: 12, color: overdueClose ? 'var(--error-main)' : 'var(--text-2)', fontWeight: overdueClose ? 650 : 450 }}>
                        {new Date(d.expectedClose).toLocaleDateString('en-GB', { day: '2-digit', month: 'short' })}{overdueClose ? ' · overdue' : ''}
                      </span>
                    ) : <span className="mn-mono mn-muted" style={{ fontSize: 12 }}>—</span>}
                  </td>
                  <td>
                    <span className={`mn-chip mn-chip--rel-${d.leadId ? 'lead' : 'client'}`}>
                      <Icon name={d.leadId ? 'users' : 'building-2'} size="xs" stroke="2" />{d.leadId ? 'lead' : 'client'}
                    </span>
                  </td>
                  <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{relTime(new Date(d.updatedAt))}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 ? (
          <div className="mn-empty">
            <Icon name="briefcase" size="lg" />
            <div className="mn-empty-msg">No deals in this view.</div>
          </div>
        ) : null}
      </div>
    </React.Fragment>
  );
}

Object.assign(window, { DealsList, DealStageChip, DEAL_STAGES, ACTIVE_STAGES, dealIsActive, fmtMoney, scopeDeals });
