// Deadlines, Admin auto-pilot, Money, Pipeline, Wins
// These are the "big picture, structural" modules.

function Deadlines() {
  const { state } = useStore();
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  return (
    <section className="mc-card">
      <div className="mc-card-hd">
        <div className="lbl"><Icons.Clock className="ico" size={18}/> Deadlines</div>
        <span className="mc-meta">{state.deadlines.length} on the horizon</span>
      </div>
      <div className="mc-deadlines">
        {state.deadlines.map((d) => {
          const due = new Date(d.due);
          const days = Math.max(0, Math.round((due - today) / 86400000));
          const label = due.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' });
          return (
            <div key={d.id} className={`mc-dl ${d.bucket}`}>
              <div className="days">{days}<small>d</small></div>
              <div className="what">
                <div className="name">{d.name}</div>
                <div className="ctx">{d.ctx}</div>
              </div>
              <div className="when">{label}</div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// --- Admin Auto-pilot --------------------------------------------------

const ADMIN_META = {
  'invoice-overdue': { ico: 'Banknote', title: 'Invoice overdue' },
  'invoice-send':    { ico: 'Banknote', title: 'Invoices to send' },
  'vat':             { ico: 'Receipt',  title: 'VAT filing' },
  'expenses':        { ico: 'Receipt',  title: 'Expenses' },
  'contract':        { ico: 'FilePen',  title: 'Contract' },
  'subscriptions':   { ico: 'Repeat',   title: 'Subscriptions' },
  'inbox':           { ico: 'Mail',     title: 'Email inbox' },
  'tax-q3':          { ico: 'Receipt',  title: 'Q3 income tax' },
};

function Admin() {
  const { state, completeAdmin, addWin } = useStore();
  return (
    <section className="mc-card" style={{ flex: 1 }}>
      <div className="mc-card-hd">
        <div className="lbl"><Icons.Refresh className="ico" size={18}/> Admin auto-pilot</div>
        <span className="mc-meta">structural — don't think, just do</span>
      </div>
      <div className="mc-admin">
        {state.admin.map((a) => {
          const meta = ADMIN_META[a.kind] || { ico: 'Refresh', title: a.kind };
          const Ico = Icons[meta.ico] || Icons.Refresh;
          return (
            <div key={a.id} className={`mc-admin-item ${a.sev}`}
                 onClick={() => { addWin(`Handled: ${meta.title.toLowerCase()}`); completeAdmin(a.id); }}>
              <span className="pill"/>
              <div className="top">
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                  <Ico size={12}/> {meta.title}
                </span>
                <span className="when">{a.when}</span>
              </div>
              <div className="count">{a.count}</div>
              <div className="what">{a.who}</div>
              <div className="do">{a.do} <Icons.ArrowR size={11}/></div>
            </div>
          );
        })}
        {state.admin.length === 0 && (
          <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: 28, color: 'var(--fg-3)' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <Icons.Check size={16}/> Admin queue is empty. Rare. Beautiful.
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

// --- Money snapshot ----------------------------------------------------

function Money() {
  const { state } = useStore();
  const m = state.money;
  const net = m.inMonth - m.outMonth;
  const fmt = (n) => m.currency + n.toLocaleString('en-US');
  const maxIn  = Math.max(...m.inSpark);
  const maxOut = Math.max(...m.outSpark);

  return (
    <section className="mc-card">
      <div className="mc-card-hd">
        <div className="lbl"><Icons.Trend className="ico" size={18}/> Money</div>
        <span className="mc-meta">this month, EUR</span>
      </div>
      <div className="mc-money">
        <div className="mc-money-row">
          <div className="mc-eyebrow">In</div>
          <div className="mc-money-num">{fmt(m.inMonth)}</div>
          <div className="mc-money-spark">
            {m.inSpark.map((v, i) => <i key={i} style={{ height: `${v / maxIn * 100}%` }}/>)}
          </div>
        </div>
        <div className="mc-money-row">
          <div className="mc-eyebrow">Out</div>
          <div className="mc-money-num out">{fmt(m.outMonth)}</div>
          <div className="mc-money-spark out">
            {m.outSpark.map((v, i) => <i key={i} style={{ height: `${v / maxOut * 100}%` }}/>)}
          </div>
        </div>
        <div className="mc-money-net">
          <div>Net <b>{fmt(net)}</b></div>
          <div className="outstanding">Outstanding <b>{fmt(m.outstanding)}</b></div>
        </div>
      </div>
    </section>
  );
}

// --- Pipeline ----------------------------------------------------------

function Pipeline() {
  const { state } = useStore();
  const lanes = ['Opportunity', 'Discovery', 'Proposal', 'Negotiation', 'Won'];
  const total = lanes.reduce((acc, l) => acc + (state.pipeline[l]?.length || 0), 0);
  return (
    <section className="mc-card">
      <div className="mc-card-hd">
        <div className="lbl"><Icons.Pipe className="ico" size={18}/> Pipeline</div>
        <span className="mc-meta">{total} deals · big picture only — drill into CRM for detail</span>
      </div>
      <div className="mc-pipe">
        {lanes.map((lane) => {
          const deals = state.pipeline[lane] || [];
          return (
            <div key={lane} className="mc-pipe-lane">
              <div className="lane-hd">
                <span>{lane}</span>
                <b>{deals.length}</b>
              </div>
              {deals.map((d, i) => (
                <div key={i} className={`mc-pipe-deal ${d.hot ? 'hot' : ''}`}>
                  <div className="name">{d.n}</div>
                  <div className="val">{d.v}{d.hot && ' · hot'}</div>
                </div>
              ))}
              {deals.length === 0 && (
                <div style={{ fontSize: 11, color: 'var(--fg-muted)', padding: '6px 4px' }}>—</div>
              )}
            </div>
          );
        })}
      </div>
    </section>
  );
}

// --- Wins log ----------------------------------------------------------

function Wins() {
  const { state } = useStore();
  return (
    <section className="mc-card">
      <div className="mc-card-hd">
        <div className="lbl"><Icons.Trophy className="ico" size={18}/> Wins</div>
        <span className="mc-meta">recent momentum</span>
      </div>
      <div className="mc-wins">
        {state.wins.slice(0, 5).map((w) => (
          <div key={w.id} className="mc-win">
            <span className="check"><Icons.Check size={11} sw={3}/></span>
            <span className="text">{w.text}</span>
            <span className="when">{w.when}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { Deadlines, Admin, Money, Pipeline, Wins });
