/* global React, Icon, KpiCard, StageChip, ChannelIcon, fmtAED, Avatar, EmptyState */
const { useState } = React;

/* ============================================================
   DASHBOARD
   Two layout variations (toggle via Tweaks):
   1. "modular" — original brief: 12-col grid, KPI cards on top
   2. "ops"     — left-rail today/calendar focus, right side metrics
   ============================================================ */

function Dashboard({ layout = 'modular', goto }) {
  return layout === 'ops' ? <DashboardOps goto={goto} /> : <DashboardModular goto={goto} />;
}

/* ----- Variation 1: Modular ----- */

function DashboardModular({ goto }) {
  return (
    <div>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Tuesday · 28 Apr 2026</div>
          <h1 className="page-title">Good morning, Sebastiano.</h1>
          <div className="page-subtitle">Pipeline weighted total · <span className="mono" style={{ color: 'var(--text)' }}>AED 187,400</span></div>
        </div>
        <div className="page-header-right">
          <button className="btn"><Icon name="refresh" size={12} /> Sync channels</button>
          <button className="btn btn-primary"><Icon name="plus" size={12} /> New deal</button>
        </div>
      </div>

      <div style={{ padding: 20 }}>
        {/* Top row: 4 KPI cards */}
        <div className="grid-12" style={{ marginBottom: 16 }}>
          <div className="col-3"><KpiCard label="Open Deals" value="14" delta="3" deltaDirection="up" sub="this week" /></div>
          <div className="col-3"><KpiCard label="Pipeline AED" value="187k" delta="12.4%" deltaDirection="up" sub="weighted" /></div>
          <div className="col-3"><KpiCard label="Calls Today" value="2" sub="1 Discovery, 1 Strategy" /></div>
          <div className="col-3"><KpiCard label="Unread" value="4" sub="across 3 channels" /></div>
        </div>

        {/* Row 2: Pipeline by stage + Today */}
        <div className="grid-12" style={{ marginBottom: 16 }}>
          <div className="col-7">
            <PipelineCard goto={goto} />
          </div>
          <div className="col-5">
            <TodayCard goto={goto} />
          </div>
        </div>

        {/* Row 3: Account health full-width */}
        <div className="grid-12" style={{ marginBottom: 16 }}>
          <div className="col-12">
            <AccountHealthCard goto={goto} />
          </div>
        </div>

        {/* Row 4: Funnels, Campaigns, Payments */}
        <div className="grid-12">
          <div className="col-4"><FunnelsCard goto={goto} /></div>
          <div className="col-4"><CampaignsCard goto={goto} /></div>
          <div className="col-4"><PaymentsCard goto={goto} /></div>
        </div>
      </div>
    </div>
  );
}

/* ----- Variation 2: Ops ----- */

function DashboardOps({ goto }) {
  return (
    <div>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Tuesday · 28 Apr 2026</div>
          <h1 className="page-title">Today.</h1>
        </div>
        <div className="page-header-right">
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginRight: 12 }}>
            <div>
              <div className="label">Pipeline</div>
              <div className="mono" style={{ fontSize: 18, fontWeight: 500, color: 'var(--text)' }}>AED 187,400</div>
            </div>
            <div style={{ width: 1, height: 28, background: 'var(--divider)' }}></div>
            <div>
              <div className="label">Open</div>
              <div className="mono" style={{ fontSize: 18, fontWeight: 500, color: 'var(--text)' }}>14</div>
            </div>
            <div style={{ width: 1, height: 28, background: 'var(--divider)' }}></div>
            <div>
              <div className="label">Replies</div>
              <div className="mono" style={{ fontSize: 18, fontWeight: 500, color: 'var(--accent)' }}>4</div>
            </div>
          </div>
          <button className="btn btn-primary"><Icon name="plus" size={12} /> New deal</button>
        </div>
      </div>

      {/* 2-col split: Today (left, larger) + everything else stacked right */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, padding: 20 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <TodayCard goto={goto} expanded />
          <PipelineCard goto={goto} />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <AccountHealthCard goto={goto} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <FunnelsCard goto={goto} />
            <CampaignsCard goto={goto} />
          </div>
          <PaymentsCard goto={goto} />
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   CARDS
   ============================================================ */

function PipelineCard({ goto }) {
  const stages = window.STAGES_OUTBOUND;
  const counts = {};
  const values = {};
  window.PIPELINE_OUTBOUND.forEach(d => {
    counts[d.stage] = (counts[d.stage] || 0) + 1;
    if (d.value) values[d.stage] = (values[d.stage] || 0) + d.value;
  });
  const maxCount = Math.max(...Object.values(counts), 1);
  const totalAed = Object.values(values).reduce((a,b) => a+b, 0);
  const weightedAed = 187400;

  return (
    <div className="card">
      <div className="card-header">
        <div>
          <h3 className="card-title">This Week's Pipeline</h3>
          <div style={{ display: 'flex', gap: 16, marginTop: 6 }}>
            <div><span className="mono" style={{ color: 'var(--text)', fontSize: 14 }}>AED {fmtAED(totalAed)}</span> <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>total</span></div>
            <div><span className="mono" style={{ color: 'var(--accent)', fontSize: 14 }}>AED {fmtAED(weightedAed)}</span> <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>weighted</span></div>
          </div>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => goto('pipeline')}>Open <Icon name="arrowRight" size={11} /></button>
      </div>
      <div style={{ padding: '14px 16px' }}>
        {stages.filter(s => counts[s.id]).map(s => (
          <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '6px 0', fontSize: 12 }}>
            <div style={{ width: 6, height: 6, borderRadius: '50%', background: s.color, flexShrink: 0 }}></div>
            <div style={{ flex: '0 0 130px', color: 'var(--text-secondary)', fontWeight: 500 }}>{s.label}</div>
            <div style={{ flex: 1, height: 4, background: 'var(--bg)', position: 'relative' }}>
              <div style={{ position: 'absolute', inset: 0, width: `${(counts[s.id]/maxCount)*100}%`, background: s.color, opacity: 0.6 }}></div>
            </div>
            <div className="mono" style={{ flex: '0 0 32px', textAlign: 'right', fontSize: 11, color: 'var(--text)' }}>{counts[s.id]}</div>
            <div className="mono" style={{ flex: '0 0 80px', textAlign: 'right', fontSize: 11, color: values[s.id] ? 'var(--text)' : 'var(--text-dim)' }}>
              {values[s.id] ? `AED ${fmtAED(values[s.id])}` : '—'}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function TodayCard({ goto, expanded = false }) {
  const events = window.CALENDAR_EVENTS.filter(e => e.day === 1);
  const tasks = [
    { id: 1, text: 'Send proposal to Globex',     done: false, due: '11:00' },
    { id: 2, text: 'Follow up · Initech pricing', done: false, due: '14:30' },
    { id: 3, text: 'Recap deck · Acme tweaks',    done: false, due: 'EOD' },
    { id: 4, text: 'Review LinkedIn responses',   done: true,  due: 'morning' },
  ];

  return (
    <div className="card" style={{ height: expanded ? 'auto' : '100%' }}>
      <div className="card-header">
        <h3 className="card-title">Today</h3>
        <button className="btn btn-ghost btn-sm" onClick={() => goto('calendar')}>Calendar <Icon name="arrowRight" size={11} /></button>
      </div>
      <div style={{ padding: '4px 0' }}>
        <div style={{ padding: '10px 16px 6px' }}>
          <div className="label">Calls</div>
        </div>
        {events.length === 0 && (
          <div style={{ padding: '8px 16px', fontSize: 12, color: 'var(--text-dim)' }}>No calls scheduled</div>
        )}
        {events.map(e => (
          <div key={e.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 16px', borderTop: '1px solid var(--divider)', cursor: 'pointer' }}
               onClick={() => goto('calendar')}>
            <div className="mono" style={{ flex: '0 0 50px', fontSize: 12, color: 'var(--text)' }}>
              {String(Math.floor(e.start)).padStart(2,'0')}:{String(Math.round((e.start%1)*60)).padStart(2,'0')}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--text)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{e.title}</div>
            </div>
            <span className="chip" style={{
              borderColor: e.type === 'discovery' ? 'rgba(249,115,22,0.3)' : 'rgba(234,179,8,0.3)',
              color: e.type === 'discovery' ? '#f97316' : '#eab308',
              background: 'transparent',
            }}>
              {e.type === 'discovery' ? 'Discovery' : 'Strategy'}
            </span>
          </div>
        ))}

        <div style={{ padding: '14px 16px 6px', borderTop: '1px solid var(--divider)', marginTop: 4 }}>
          <div className="label">Tasks · {tasks.filter(t => !t.done).length} due</div>
        </div>
        {tasks.map(t => (
          <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 16px', fontSize: 12 }}>
            <div style={{
              width: 14, height: 14, border: '1px solid var(--divider)', display: 'flex',
              alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              background: t.done ? 'var(--accent)' : 'transparent',
              borderColor: t.done ? 'var(--accent)' : 'var(--divider)',
            }}>
              {t.done && <Icon name="check" size={10} style={{ color: '#0a0a0a' }} />}
            </div>
            <div style={{ flex: 1, color: t.done ? 'var(--text-dim)' : 'var(--text)', textDecoration: t.done ? 'line-through' : 'none' }}>{t.text}</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>{t.due}</div>
          </div>
        ))}

        <div style={{ padding: '14px 16px 12px', borderTop: '1px solid var(--divider)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 12 }}>
          <Icon name="inbox" size={14} style={{ color: 'var(--text-dim)' }} />
          <div style={{ flex: 1, fontSize: 12 }}>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>4 unread messages</span>
            <span style={{ color: 'var(--text-dim)', marginLeft: 6 }}>across LinkedIn, WhatsApp, IG</span>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => goto('inbox')}>Open</button>
        </div>
      </div>
    </div>
  );
}

function AccountHealthCard({ goto }) {
  const channels = window.CHANNELS.filter(c => c.kind !== 'email');
  return (
    <div className="card">
      <div className="card-header">
        <h3 className="card-title">Account Health · Messaging</h3>
        <button className="btn btn-ghost btn-sm" onClick={() => goto('settings')}>Settings <Icon name="arrowRight" size={11} /></button>
      </div>
      <div style={{ padding: 0 }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '24px 1fr 90px 120px 60px 30px',
          padding: '10px 16px', borderBottom: '1px solid var(--divider)',
          fontSize: 9, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)',
        }}>
          <div></div>
          <div>Account</div>
          <div>Channel</div>
          <div>Sends today</div>
          <div style={{ textAlign: 'right' }}>Ramp</div>
          <div></div>
        </div>
        {channels.map(ch => {
          const dotClass = ch.status === 'active' ? 'dot-green' : ch.status === 'paused' ? 'dot-yellow' : 'dot-red';
          const pct = (ch.sendsToday / ch.cap) * 100;
          return (
            <div key={ch.id} style={{
              display: 'grid', gridTemplateColumns: '24px 1fr 90px 120px 60px 30px',
              padding: '10px 16px', borderBottom: '1px solid var(--divider)', alignItems: 'center', fontSize: 12,
            }}>
              <span className={`status-dot ${dotClass}`}></span>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 500, color: 'var(--text)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{ch.label}</div>
                {ch.errorMsg && <div style={{ fontSize: 11, color: 'var(--red)' }}>{ch.errorMsg}</div>}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--text-secondary)' }}>
                <ChannelIcon kind={ch.kind} size={12} />
                <span style={{ textTransform: 'capitalize', fontSize: 11 }}>{ch.kind}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ flex: 1, height: 4, background: 'var(--bg)', position: 'relative', maxWidth: 70 }}>
                  <div style={{ position: 'absolute', inset: 0, width: `${pct}%`, background: pct > 90 ? 'var(--orange)' : 'var(--accent)' }}></div>
                </div>
                <span className="mono" style={{ fontSize: 11, color: 'var(--text-secondary)' }}>{ch.sendsToday}/{ch.cap}</span>
              </div>
              <div className="mono" style={{ textAlign: 'right', fontSize: 11, color: 'var(--text-secondary)' }}>W{ch.rampWeek}</div>
              <button className="btn btn-ghost btn-icon" style={{ width: 24, height: 24 }}><Icon name="more" size={13} /></button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function FunnelsCard({ goto }) {
  const funnels = window.FUNNELS.filter(f => f.status === 'live').slice(0, 5);
  return (
    <div className="card">
      <div className="card-header">
        <h3 className="card-title">Funnels · This Week</h3>
        <button className="btn btn-ghost btn-sm" onClick={() => goto('funnels')}><Icon name="arrowRight" size={11} /></button>
      </div>
      <div>
        {funnels.map(f => (
          <div key={f.id} style={{ padding: '10px 16px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 12, fontSize: 12 }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 500, color: 'var(--text)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{f.name}</div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>/{f.slug}</div>
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--text)' }}>{f.submissions}</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--accent)', flex: '0 0 50px', textAlign: 'right' }}>{f.conversion}%</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function CampaignsCard({ goto }) {
  const active = window.CAMPAIGNS.filter(c => c.status === 'active');
  return (
    <div className="card">
      <div className="card-header">
        <h3 className="card-title">Campaigns · Active</h3>
        <button className="btn btn-ghost btn-sm" onClick={() => goto('campaigns')}><Icon name="arrowRight" size={11} /></button>
      </div>
      <div>
        {active.map(c => (
          <div key={c.id} style={{ padding: '10px 16px', borderBottom: '1px solid var(--divider)' }}>
            <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--text)', marginBottom: 6, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{c.name}</div>
            <div style={{ display: 'flex', gap: 14, fontSize: 10 }}>
              <div><div className="mono" style={{ color: 'var(--text)' }}>{c.sent}</div><div style={{ color: 'var(--text-dim)' }}>sent</div></div>
              <div><div className="mono" style={{ color: 'var(--text)' }}>{c.opens}%</div><div style={{ color: 'var(--text-dim)' }}>opens</div></div>
              <div><div className="mono" style={{ color: 'var(--accent)' }}>{c.replies}%</div><div style={{ color: 'var(--text-dim)' }}>replies</div></div>
              <div><div className="mono" style={{ color: c.bounces > 1 ? 'var(--orange)' : 'var(--text)' }}>{c.bounces}%</div><div style={{ color: 'var(--text-dim)' }}>bounces</div></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PaymentsCard({ goto }) {
  const newPayments = window.PAYMENTS.filter(p => p.status === 'paid').slice(0, 3);
  const expected = 26000;
  const mrr = 53000;
  return (
    <div className="card">
      <div className="card-header">
        <h3 className="card-title">Payments · This Week</h3>
        <button className="btn btn-ghost btn-sm" onClick={() => goto('payments')}><Icon name="arrowRight" size={11} /></button>
      </div>
      <div style={{ padding: '14px 16px', display: 'flex', gap: 16, borderBottom: '1px solid var(--divider)' }}>
        <div style={{ flex: 1 }}>
          <div className="label" style={{ marginBottom: 4 }}>Expected</div>
          <div className="mono" style={{ fontSize: 16, color: 'var(--text)' }}>AED {fmtAED(expected)}</div>
        </div>
        <div style={{ flex: 1 }}>
          <div className="label" style={{ marginBottom: 4 }}>MRR proj.</div>
          <div className="mono" style={{ fontSize: 16, color: 'var(--accent)' }}>AED {fmtAED(mrr)}</div>
        </div>
      </div>
      {newPayments.map(p => (
        <div key={p.id} style={{ padding: '8px 16px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 8, fontSize: 11 }}>
          <Icon name="check" size={12} style={{ color: 'var(--accent)' }} />
          <div style={{ flex: 1, color: 'var(--text-secondary)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{p.deal}</div>
          <div className="mono" style={{ color: 'var(--text)' }}>{fmtAED(p.amount)}</div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Dashboard });
