// Shared UI primitives — donut chart, transaction row, account card, etc.

const { useState: finUseState, useMemo: finUseMemo, useEffect: finUseEffect, useRef: finUseRef } = React;

// ─────────────────────────────────────────────────────────────
// Donut Chart (SVG) — month spending by category
// ─────────────────────────────────────────────────────────────
function DonutChart({ data, size = 220, thickness = 22, total, label = "Gastado", caption }) {
  const Icon = window.FinanzasIcon;
  const sum = data.reduce((s, d) => s + d.total, 0) || 1;
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  const cx = size / 2, cy = size / 2;
  let offset = 0;
  const segments = data.map((d) => {
    const frac = d.total / sum;
    const len = frac * c;
    const seg = (
      <circle key={d.id}
        cx={cx} cy={cy} r={r}
        fill="none"
        stroke={d.color}
        strokeWidth={thickness}
        strokeDasharray={`${len} ${c - len}`}
        strokeDashoffset={-offset}
        style={{ transition: "stroke-dasharray 360ms cubic-bezier(0.16,1,0.3,1)" }}
      />
    );
    offset += len;
    return seg;
  });
  return (
    <div style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", gap: 0 }}>
      <div style={{ position: "relative", width: size, height: size }}>
        <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
          {/* Background track */}
          <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--bx-line)" strokeWidth={thickness} />
          {segments}
        </svg>
        <div style={{
          position: "absolute", inset: 0, display: "flex",
          flexDirection: "column", alignItems: "center", justifyContent: "center",
          gap: 2,
        }}>
          <div style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--bx-ink-3)", fontWeight: 600 }}>{label}</div>
          <div style={{
            fontFamily: "'Bebas Neue', sans-serif", fontSize: 38,
            color: "var(--bx-ink-1)", letterSpacing: "0.01em", lineHeight: 1, fontWeight: 400,
          }}>{window.fmtMXN(total).replace("$", "$ ")}</div>
          {caption ? (
            <div style={{ fontSize: 11, color: "var(--bx-ink-3)", marginTop: 2 }}>{caption}</div>
          ) : null}
        </div>
      </div>
    </div>
  );
}

// Mini sparkline (for daily-spend trend on mobile)
function Sparkline({ values, width = 260, height = 56, color = "var(--bx-navy-700)" }) {
  if (!values || !values.length) return null;
  const max = Math.max(...values, 1);
  const step = width / (values.length - 1 || 1);
  const pts = values.map((v, i) => [i * step, height - (v / max) * (height - 6) - 3]);
  const d = pts.map(([x, y], i) => `${i === 0 ? "M" : "L"}${x.toFixed(1)} ${y.toFixed(1)}`).join(" ");
  const area = `${d} L${width} ${height} L0 ${height} Z`;
  return (
    <svg width={width} height={height} style={{ display: "block" }}>
      <defs>
        <linearGradient id="sparkFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.18" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sparkFill)" />
      <path d={d} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      {pts.length > 0 && (
        <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="3" fill={color} />
      )}
    </svg>
  );
}

// Category icon disk (colored circle with white icon)
function CatBadge({ catId, size = 40, soft = true }) {
  const Icon = window.FinanzasIcon;
  const cat = window.catBy(catId);
  if (!cat) return null;
  return (
    <div style={{
      width: size, height: size, borderRadius: size / 2,
      background: soft ? `${cat.color}1A` : cat.color,
      color: soft ? cat.color : "#fff",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      flexShrink: 0,
    }}>
      <Icon name={cat.icon} size={Math.round(size * 0.5)} stroke={2} />
    </div>
  );
}

// Single transaction row (used desktop + mobile)
function TxRow({ tx, onEdit, dense = false, showDay = false, last = false }) {
  const cat = window.catBy(tx.cat);
  const acc = window.accBy(tx.acc);
  const isIncome = tx.amount > 0;
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: dense ? "auto 1fr auto" : "auto 1fr auto auto",
      alignItems: "center",
      gap: dense ? 12 : 16,
      padding: dense ? "12px 0" : "14px 4px",
      borderBottom: last ? "none" : "1px solid var(--bx-line)",
      cursor: "pointer",
    }}
    onClick={() => onEdit?.(tx)}>
      <CatBadge catId={tx.cat} size={dense ? 36 : 40} />
      <div style={{ minWidth: 0 }}>
        <div style={{
          fontFamily: "Inter, sans-serif", fontSize: dense ? 14 : 14, fontWeight: 600,
          color: "var(--bx-ink-1)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
        }}>{tx.desc}</div>
        <div style={{ fontSize: 12, color: "var(--bx-ink-3)", display: "flex", gap: 8, alignItems: "center", marginTop: 2 }}>
          <span>{cat.label}</span>
          <span style={{ width: 2, height: 2, borderRadius: 1, background: "var(--bx-ink-4)" }} />
          <span>{acc.name}</span>
          {tx.tags?.includes("recurring") && (
            <>
              <span style={{ width: 2, height: 2, borderRadius: 1, background: "var(--bx-ink-4)" }} />
              <span style={{
                fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase",
                color: "var(--bx-navy-700)", fontWeight: 600,
              }}>Recurrente</span>
            </>
          )}
        </div>
      </div>
      {!dense && (
        <div style={{ fontSize: 12, color: "var(--bx-ink-3)", textAlign: "right" }}>
          {window.relTime(tx.date)}
        </div>
      )}
      <div style={{
        fontFamily: "'JetBrains Mono', ui-monospace, monospace",
        fontSize: dense ? 14 : 15, fontWeight: 600,
        fontFeatureSettings: "'tnum'",
        color: isIncome ? "var(--bx-success)" : "var(--bx-ink-1)",
        whiteSpace: "nowrap",
      }}>
        {window.fmtMXN(tx.amount, { sign: true })}
      </div>
    </div>
  );
}

// Account card — used in account strip
function AccountCard({ acc, compact = false, active = false, onClick }) {
  const Icon = window.FinanzasIcon;
  const iconName = acc.type === "Crédito" ? "card" : acc.type === "Cash" ? "wallet" : acc.type === "Inversión" ? "piggy" : "bank";
  const negative = acc.balance < 0;
  return (
    <button onClick={onClick} style={{
      textAlign: "left",
      background: active ? "var(--bx-navy-700)" : "var(--bx-paper)",
      color: active ? "#fff" : "var(--bx-ink-1)",
      border: active ? "1px solid var(--bx-navy-700)" : "1px solid var(--bx-line)",
      borderRadius: 10, padding: compact ? "12px 14px" : "16px 18px",
      cursor: "pointer", transition: "all 220ms cubic-bezier(0.2,0.8,0.2,1)",
      display: "flex", flexDirection: "column", gap: compact ? 8 : 12,
      minWidth: compact ? 160 : 200,
      flexShrink: 0,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{
          width: 32, height: 32, borderRadius: 8,
          background: active ? "rgba(255,255,255,.12)" : "var(--bx-bg-tint)",
          color: active ? "#fff" : "var(--bx-navy-700)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
        }}><Icon name={iconName} size={16} stroke={2} /></div>
        <div style={{
          fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 600,
          color: active ? "rgba(255,255,255,.7)" : "var(--bx-ink-3)",
        }}>{acc.type}</div>
      </div>
      <div>
        <div style={{ fontSize: 12, fontWeight: 500, opacity: active ? .85 : 1, color: active ? "#fff" : "var(--bx-ink-2)" }}>
          {acc.name}{acc.last4 ? ` ··${acc.last4}` : ""}
        </div>
        <div style={{
          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontSize: compact ? 16 : 20, fontWeight: 700, marginTop: 4,
          fontFeatureSettings: "'tnum'",
          color: active ? "#fff" : (negative ? "var(--bx-danger)" : "var(--bx-ink-1)"),
        }}>{window.fmtMXN(acc.balance, { sign: false })}</div>
      </div>
    </button>
  );
}

// Budget row with progress bar
function BudgetRow({ b }) {
  const cat = window.catBy(b.cat);
  const pct = Math.min(1, b.spent / b.limit);
  const over = pct >= 0.9;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8, padding: "10px 0" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <CatBadge catId={b.cat} size={26} />
          <div style={{ fontSize: 13, fontWeight: 600, color: "var(--bx-ink-1)" }}>{cat.label}</div>
        </div>
        <div style={{
          fontFamily: "'JetBrains Mono', monospace", fontSize: 12,
          color: "var(--bx-ink-3)", fontFeatureSettings: "'tnum'",
        }}>
          <span style={{ color: over ? "var(--bx-danger)" : "var(--bx-ink-1)", fontWeight: 600 }}>
            {window.fmtMXN(b.spent)}
          </span>
          <span> / {window.fmtMXN(b.limit)}</span>
        </div>
      </div>
      <div style={{ height: 6, borderRadius: 999, background: "var(--bx-line)", overflow: "hidden" }}>
        <div style={{
          width: `${pct * 100}%`, height: "100%",
          background: over ? "var(--bx-danger)" : cat.color,
          borderRadius: 999,
          transition: "width 360ms cubic-bezier(0.16,1,0.3,1)",
        }} />
      </div>
    </div>
  );
}

// Legend item under donut
function LegendItem({ d, total }) {
  const pct = ((d.total / total) * 100).toFixed(0);
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "6px 0", gap: 12 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
        <span style={{ width: 8, height: 8, borderRadius: 2, background: d.color, flexShrink: 0 }} />
        <span style={{ fontSize: 13, color: "var(--bx-ink-1)", fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.label}</span>
      </div>
      <div style={{ display: "flex", gap: 10, alignItems: "baseline" }}>
        <span style={{ fontSize: 11, color: "var(--bx-ink-3)", fontFeatureSettings: "'tnum'", fontFamily: "'JetBrains Mono', monospace" }}>{pct}%</span>
        <span style={{ fontSize: 13, color: "var(--bx-ink-1)", fontWeight: 600, fontFamily: "'JetBrains Mono', monospace", fontFeatureSettings: "'tnum'" }}>
          {window.fmtMXN(d.total)}
        </span>
      </div>
    </div>
  );
}

// Status bar for iOS frame
function IOSStatusBar({ dark = false }) {
  const fg = dark ? "#fff" : "var(--bx-ink-1)";
  return (
    <div style={{
      height: 44, display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "0 28px", fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui",
      color: fg, fontSize: 15, fontWeight: 600,
      flexShrink: 0,
    }}>
      <div>9:41</div>
      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
        {/* Signal */}
        <svg width="17" height="11" viewBox="0 0 17 11" fill={fg}>
          <rect x="0"  y="7" width="3" height="4" rx="1"/>
          <rect x="4"  y="5" width="3" height="6" rx="1"/>
          <rect x="8"  y="3" width="3" height="8" rx="1"/>
          <rect x="12" y="0" width="3" height="11" rx="1"/>
        </svg>
        {/* Wifi */}
        <svg width="15" height="11" viewBox="0 0 15 11" fill={fg}>
          <path d="M7.5 1c2.8 0 5.3 1 7.2 2.6L13.4 5C12 3.8 9.9 3 7.5 3S3 3.8 1.6 5L0.3 3.6C2.2 2 4.7 1 7.5 1Zm0 3.5c1.9 0 3.6.7 4.9 1.8L11.1 7.7c-1-.8-2.3-1.3-3.6-1.3s-2.6.5-3.6 1.3L2.6 6.3C3.9 5.2 5.6 4.5 7.5 4.5Zm0 3.5c1 0 1.9.4 2.6 1L7.5 11 4.9 9c.7-.6 1.6-1 2.6-1Z"/>
        </svg>
        {/* Battery */}
        <svg width="27" height="13" viewBox="0 0 27 13" fill="none">
          <rect x="0.5" y="0.5" width="22" height="12" rx="3" stroke={fg} opacity="0.4"/>
          <rect x="2"   y="2"   width="19" height="9"  rx="1.5" fill={fg}/>
          <rect x="23.5" y="4" width="2" height="5" rx="1" fill={fg} opacity="0.4"/>
        </svg>
      </div>
    </div>
  );
}

Object.assign(window, {
  DonutChart, Sparkline, CatBadge, TxRow, AccountCard, BudgetRow, LegendItem, IOSStatusBar,
});
