// screen-payments.jsx — payments dashboard

function PaymentsScreen({ orders, currentUser, onOpenOrder }) {
  const isOwner = currentUser.role === 'owner';

  const today = React.useMemo(() => {
    const d = new Date(); d.setHours(0, 0, 0, 0); return d;
  }, []);

  const thisMonthStart = React.useMemo(() => {
    const d = new Date(today); d.setDate(1); return d;
  }, [today]);

  const lastMonthStart = React.useMemo(() => {
    const d = new Date(thisMonthStart); d.setMonth(d.getMonth() - 1); return d;
  }, [thisMonthStart]);

  const monthName = thisMonthStart.toLocaleString('sq-AL', { month: 'long', year: 'numeric' });

  // ── Core stats ─────────────────────────────────────────────────────────

  const stats = React.useMemo(() => {
    let revenueMonth = 0, revenueLastMonth = 0;
    let outstanding = 0, unpaidCount = 0, depositCount = 0, paidCount = 0;

    orders.forEach(o => {
      const p = o.payment;
      if (!p || o.status === 'cancelled') return;
      const total = p.total_price || 0;
      const deposit = p.deposit_amount || 0;
      const state = window.paymentState(p);

      // Revenue: sum by the date the order was fully paid
      if (state === 'paid' && p.fully_paid_at) {
        const paidDate = new Date(p.fully_paid_at.slice(0, 10));
        if (paidDate >= thisMonthStart) revenueMonth += total;
        else if (paidDate >= lastMonthStart && paidDate < thisMonthStart) revenueLastMonth += total;
      }

      if (state === 'unpaid')        { outstanding += total;           unpaidCount++; }
      else if (state === 'deposit')  { outstanding += (total - deposit); depositCount++; }
      else if (state === 'paid')     { paidCount++; }
    });

    const trend = revenueLastMonth > 0
      ? ((revenueMonth - revenueLastMonth) / revenueLastMonth * 100).toFixed(0)
      : null;

    return { revenueMonth, revenueLastMonth, trend, outstanding, unpaidCount, depositCount, paidCount };
  }, [orders, thisMonthStart, lastMonthStart]);

  // ── 30-day sparkline from real order due dates ─────────────────────────

  const { sparkline, sparkDates } = React.useMemo(() => {
    const DAYS = 30;
    const values = new Array(DAYS).fill(0);
    const dates = [];

    for (let i = 0; i < DAYS; i++) {
      const d = new Date(today);
      d.setDate(d.getDate() - (DAYS - 1 - i));
      dates.push(d);
    }

    orders.forEach(o => {
      if (o.status === 'cancelled' || !o.payment?.total_price) return;
      const due = new Date(o.due_date);
      due.setHours(0, 0, 0, 0);
      const idx = Math.round((due - dates[0]) / 86400000);
      if (idx >= 0 && idx < DAYS) values[idx] += o.payment.total_price;
    });

    return { sparkline: values, sparkDates: dates };
  }, [orders, today]);

  const sparkMax = Math.max(...sparkline, 1);
  const sparkPath = sparkline.map((v, i) => {
    const x = (i / (sparkline.length - 1)) * 100;
    const y = 100 - (v / sparkMax) * 90; // 90% height so line doesn't touch top edge
    return `${i === 0 ? 'M' : 'L'} ${x.toFixed(2)} ${y.toFixed(2)}`;
  }).join(' ');
  const sparkFillPath = sparkPath + ` L 100 100 L 0 100 Z`;

  const fmtDate = (d) => d.toLocaleDateString('sq-AL', { day: 'numeric', month: 'short' });

  // ── Month at a glance (real data) ──────────────────────────────────────

  const monthStats = React.useMemo(() => {
    const thisMonth = orders.filter(o =>
      o.status !== 'cancelled' &&
      new Date(o.due_date) >= thisMonthStart &&
      new Date(o.due_date) < new Date(thisMonthStart.getFullYear(), thisMonthStart.getMonth() + 1, 1)
    );

    const standard  = thisMonth.filter(o => o.type === 'standard').length;
    const custom    = thisMonth.filter(o => o.type === 'custom').length;
    const baklava   = thisMonth.filter(o => o.type === 'baklava').length;

    const withPrice = orders.filter(o => o.status !== 'cancelled' && o.payment?.total_price > 0);
    const avg = withPrice.length
      ? withPrice.reduce((s, o) => s + o.payment.total_price, 0) / withPrice.length
      : 0;

    const flavourCounts = {};
    orders.forEach(o => {
      if (o.flavour) flavourCounts[o.flavour] = (flavourCounts[o.flavour] || 0) + 1;
    });
    const topFlavour = Object.entries(flavourCounts).sort((a, b) => b[1] - a[1])[0];

    return { standard, custom, baklava, avg, topFlavour };
  }, [orders, thisMonthStart]);

  // ── Lists ──────────────────────────────────────────────────────────────

  const topCustomers = React.useMemo(() => {
    const map = {};
    orders.forEach(o => {
      const total = o.payment?.total_price || 0;
      if (!map[o.customer_name]) map[o.customer_name] = { name: o.customer_name, total: 0, count: 0 };
      map[o.customer_name].total += total;
      map[o.customer_name].count++;
    });
    return Object.values(map).sort((a, b) => b.total - a.total).slice(0, 5);
  }, [orders]);

  const outstandingOrders = orders.filter(o => {
    const state = window.paymentState(o.payment);
    return o.status !== 'cancelled' && (state === 'unpaid' || state === 'deposit');
  }).sort((a, b) => new Date(a.due_date) - new Date(b.due_date));

  const recentPaid = orders.filter(o => o.payment?.fully_paid_at)
    .sort((a, b) => new Date(b.payment.fully_paid_at) - new Date(a.payment.fully_paid_at))
    .slice(0, 5);

  // ── Trend label ────────────────────────────────────────────────────────

  const trendLabel = stats.trend !== null
    ? `${stats.trend > 0 ? '+' : ''}${stats.trend}% ndaj muajit të kaluar`
    : 'Muaji i parë me të dhëna';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>

      {/* Stats row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
        <StatCard label={`Të ardhura · ${monthName}`} value={window.formatEUR(stats.revenueMonth)} accent="var(--green)" trend={trendLabel} big />
        <StatCard label="Papaguar gjithsej" value={window.formatEUR(stats.outstanding)} accent="var(--amber)" trend={`${stats.unpaidCount + stats.depositCount} porosi`} />
        <StatCard label="Pa depozitë" value={String(stats.unpaidCount)} accent="var(--red)" trend={`${stats.depositCount} vetëm depozitë`} />
        <StatCard label="Paguar plotësisht" value={String(stats.paidCount)} accent="var(--green)" trend="nga të gjitha porositë" />
      </div>

      {/* Sparkline + month breakdown */}
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 2fr) minmax(0, 1fr)', gap: 16 }} className="payments-grid">
        <div className="card">
          <SectionHeader
            title="Trendi i porosive"
            subtitle="30 ditët e fundit · vlera e porosive sipas afatit"
            action={
              stats.trend !== null && Number(stats.trend) > 0 ? (
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--green)', fontSize: 13, fontWeight: 600 }}>
                  <IconTrendingUp size={14} color="var(--green)" /> Në rritje
                </div>
              ) : null
            }
          />

          {sparkline.every(v => v === 0) ? (
            <div style={{ aspectRatio: '3 / 1', display: 'grid', placeItems: 'center' }}>
              <p className="muted" style={{ margin: 0, fontSize: 13 }}>Asnjë porosi me çmim në 30 ditët e fundit</p>
            </div>
          ) : (
            <>
              <div style={{ aspectRatio: '3 / 1', position: 'relative' }}>
                <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: '100%', height: '100%' }}>
                  <defs>
                    <linearGradient id="spark-grad" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0" stopColor="var(--rose)" stopOpacity="0.22"/>
                      <stop offset="1" stopColor="var(--rose)" stopOpacity="0"/>
                    </linearGradient>
                  </defs>
                  <path d={sparkFillPath} fill="url(#spark-grad)" />
                  <path d={sparkPath} stroke="var(--rose)" fill="none" vectorEffect="non-scaling-stroke" style={{ strokeWidth: 2 }} />
                  {sparkline.map((v, i) => {
                    if (v === 0) return null;
                    const x = (i / (sparkline.length - 1)) * 100;
                    const y = 100 - (v / sparkMax) * 90;
                    return <circle key={i} cx={x} cy={y} r="0.6" fill="var(--rose)" />;
                  })}
                </svg>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11.5, color: 'var(--ink-mute)' }}>
                <span>{fmtDate(sparkDates[0])}</span>
                <span>{fmtDate(sparkDates[14])}</span>
                <span>{fmtDate(sparkDates[29])}</span>
              </div>
            </>
          )}
        </div>

        <div className="card-warm">
          <SectionHeader title={`${monthName.split(' ')[0]} · pasqyrë`} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <MonthRow label="Torta standarde" value={monthStats.standard} sub="këtë muaj" />
            <MonthRow label="Dizajne të personalizuara" value={monthStats.custom} sub="këtë muaj" />
            <MonthRow label="Bakllava" value={monthStats.baklava} sub="këtë muaj" />
            <MonthRow label="Vlera mesatare" value={window.formatEUR(monthStats.avg)} sub="të gjitha porositë" />
            {monthStats.topFlavour && (
              <MonthRow label="Shija kryesore" value={monthStats.topFlavour[0]} sub={`${monthStats.topFlavour[1]} porosi`} />
            )}
          </div>
        </div>
      </div>

      {/* Outstanding */}
      <div className="card">
        <SectionHeader
          title="Bilancet e papaguara"
          subtitle={`${outstandingOrders.length} porosi pret pagesë`}
        />
        {outstandingOrders.length === 0 ? (
          <p className="muted" style={{ textAlign: 'center', padding: 30, margin: 0 }}>Asnjë bilanc i papaguar.</p>
        ) : (
          <div>
            {outstandingOrders.map(o => {
              const owed = (o.payment?.total_price || 0) - (o.payment?.deposit_amount || 0);
              return (
                <div key={o.id} onClick={() => onOpenOrder(o.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 14, padding: '14px 6px',
                  borderTop: '1px solid var(--line)', cursor: 'pointer',
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--cream-2)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <div style={{ width: 44, height: 44, borderRadius: 10, overflow: 'hidden', flexShrink: 0 }}>
                    <CakeArt name={o.art} style={{ width: '100%', height: '100%' }} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 15 }}>{o.customer_name}</div>
                    <div className="muted" style={{ fontSize: 12.5 }}>
                      #{o.id.slice(-4)} · {window.relativeDay(o.due_date).toLowerCase()}
                      {o.type === 'custom' && !o.payment?.total_price && ' · çmim i pavendosur'}
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="display tabular" style={{ fontSize: 18, fontWeight: 600 }}>
                      {o.payment?.total_price ? window.formatEUR(owed) : '—'}
                    </div>
                    <div className="muted" style={{ fontSize: 11.5 }}>
                      prej {window.formatEUR(o.payment?.total_price)}
                    </div>
                  </div>
                  <PaymentBadge payment={o.payment} />
                  <IconChevronRight size={16} color="var(--ink-mute)" />
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Recent paid + top customers */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16 }}>
        <div className="card">
          <SectionHeader title="Paguar së fundmi" />
          {recentPaid.length === 0 ? (
            <p className="muted" style={{ margin: 0 }}>Asnjë porosi e paguar akoma.</p>
          ) : recentPaid.map(o => (
            <div key={o.id} onClick={() => onOpenOrder(o.id)} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '10px 4px',
              borderTop: '1px solid var(--line)', cursor: 'pointer',
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 8, overflow: 'hidden', flexShrink: 0 }}>
                <CakeArt name={o.art} style={{ width: '100%', height: '100%' }} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 500, fontSize: 14 }}>{o.customer_name}</div>
                <div className="muted" style={{ fontSize: 12 }}>{window.relativeDay(o.payment.fully_paid_at.slice(0, 10))}</div>
              </div>
              <div className="tabular display" style={{ fontSize: 16, fontWeight: 600, color: 'var(--green)' }}>
                +{window.formatEUR(o.payment.total_price)}
              </div>
            </div>
          ))}
        </div>

        {isOwner && (
          <div className="card">
            <SectionHeader title="Klientët kryesorë" subtitle="Sipas vlerës totale të porosive" />
            {topCustomers.length === 0 ? (
              <p className="muted" style={{ margin: 0 }}>Asnjë porosi akoma.</p>
            ) : topCustomers.map((c, i) => (
              <div key={c.name} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '10px 4px',
                borderTop: i ? '1px solid var(--line)' : 'none',
              }}>
                <Avatar name={c.name} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 500, fontSize: 14 }}>{c.name}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{c.count} {c.count === 1 ? 'porosi' : 'porosi'}</div>
                </div>
                <div className="tabular display" style={{ fontSize: 16, fontWeight: 600 }}>
                  {window.formatEUR(c.total)}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {!isOwner && (
        <div style={{ padding: 16, background: 'var(--cream-2)', borderRadius: 12, fontSize: 13.5, color: 'var(--ink-2)', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <IconLock size={16} color="var(--ink-mute)" style={{ marginTop: 2 }}/>
          <div>
            <strong>Pamje e kufizuar</strong> — historia e plotë e pagesave është vetëm për pronarin. Mund të regjistroni depozita dhe të shënoni porositë si të paguara plotësisht nga faqja e secilës porosi.
          </div>
        </div>
      )}
    </div>
  );
}

function StatCard({ label, value, accent, trend, big }) {
  return (
    <div style={{ padding: 18, borderRadius: 14, background: 'white', border: '1px solid var(--line)', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: accent }} />
      <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 8, fontWeight: 600 }}>{label}</div>
      <div className="display tabular" style={{ fontSize: big ? 38 : 30, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1 }}>{value}</div>
      {trend && <div className="muted" style={{ fontSize: 12, marginTop: 6 }}>{trend}</div>}
    </div>
  );
}

function MonthRow({ label, value, sub }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 12 }}>
      <span style={{ fontSize: 13.5, color: 'var(--ink-2)', flex: 1 }}>{label}</span>
      <span className="display tabular" style={{ fontWeight: 600, fontSize: 18 }}>{value}</span>
      <span className="muted" style={{ fontSize: 11.5, minWidth: 60, textAlign: 'right' }}>{sub}</span>
    </div>
  );
}

Object.assign(window, { PaymentsScreen });
