// ShipmentDiagram — animated "1 order → 3 shipments → 3 invoices" visual.
// Uses a single fixed-pixel coordinate space so SVG lines and absolutely-
// positioned cards always align, regardless of container width.

function ShipmentDiagram({ theme }) {
  const t = theme || {};
  const ink = t.ink || '#17161a';
  const muted = t.muted || '#6b6862';
  const accent = t.accent || '#2a5bff';
  const accentSoft = t.accentSoft || 'rgba(42,91,255,0.10)';
  const paper = t.paper || '#ffffff';
  const line = t.line || 'rgba(0,0,0,0.10)';
  const bg = t.bg || 'transparent';
  const radius = t.radius ?? 10;
  const mono = t.mono || "'JetBrains Mono', ui-monospace, monospace";
  const display = t.display || "'Inter', sans-serif";
  const label = t.label || muted;

  const [phase, setPhase] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setPhase(p => (p + 1) % 4), 1400);
    return () => clearInterval(id);
  }, []);

  const shipments = [
    { id: 'S-1', items: '3 items', weight: '2.4 kg', total: '$184.20', final: false },
    { id: 'S-2', items: '1 item',  weight: '0.8 kg', total: '$62.40',  final: false },
    { id: 'S-3', items: '2 items', weight: '5.1 kg', total: '$91.90',  final: true  },
  ];

  // Single coordinate space in pixels. The stage is fixed-width and centered
  // so SVG paths and absolutely-positioned cards share exact units.
  const STAGE_W = 960;          // inner stage width
  const PAD_X = 32;             // inner horizontal padding
  const PAD_TOP = 52;           // room for column headers
  const PAD_BOTTOM = 28;
  const CARD_W = 236;
  const CARD_H = 108;
  const ROW_GAP = 28;           // vertical gap between shipment rows
  const rows = shipments.length;
  const CONTENT_H = rows * CARD_H + (rows - 1) * ROW_GAP;
  const STAGE_H = PAD_TOP + CONTENT_H + PAD_BOTTOM;

  // Column x positions (left edge of each card)
  const orderX = PAD_X;
  const invX = STAGE_W - PAD_X - CARD_W;
  const shipX = Math.round((orderX + CARD_W + invX) / 2 - CARD_W / 2);

  // Card row y positions (top edge)
  const shipY = (i) => PAD_TOP + i * (CARD_H + ROW_GAP);
  const invY = (i) => shipY(i);

  // Order card is vertically centered in the content area
  const orderY = PAD_TOP + (CONTENT_H - CARD_H) / 2;

  // Connection anchor points (edge midpoints)
  const orderRight = { x: orderX + CARD_W, y: orderY + CARD_H / 2 };
  const shipLeft  = (i) => ({ x: shipX,            y: shipY(i) + CARD_H / 2 });
  const shipRight = (i) => ({ x: shipX + CARD_W,   y: shipY(i) + CARD_H / 2 });
  const invLeft   = (i) => ({ x: invX,             y: invY(i)  + CARD_H / 2 });

  const curve = (from, to) => {
    const cx = (from.x + to.x) / 2;
    return `M ${from.x} ${from.y} C ${cx} ${from.y}, ${cx} ${to.y}, ${to.x} ${to.y}`;
  };

  return (
    <div style={{
      background: bg,
      borderRadius: radius,
      border: t.border || 'none',
      overflow: 'hidden',
      width: '100%',
    }}>
      {/* Fixed-width stage; centered inside the flexible outer container. */}
      <div style={{
        width: STAGE_W,
        height: STAGE_H,
        margin: '0 auto',
        position: 'relative',
      }}>
        {/* Column headers */}
        <div style={{
          position: 'absolute',
          left: 0, right: 0, top: 22,
          display: 'flex',
          fontFamily: mono,
          fontSize: 11,
          letterSpacing: '0.1em',
          textTransform: 'uppercase',
          color: label,
        }}>
          <div style={{ position: 'absolute', left: orderX, width: CARD_W }}>Shopify order</div>
          <div style={{ position: 'absolute', left: shipX,  width: CARD_W }}>Fulfillments</div>
          <div style={{ position: 'absolute', left: invX,   width: CARD_W }}>Qixeo invoices</div>
        </div>

        {/* SVG for connecting lines — fixed pixel dimensions, same coord space */}
        <svg
          width={STAGE_W}
          height={STAGE_H}
          viewBox={`0 0 ${STAGE_W} ${STAGE_H}`}
          style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}
        >
          {/* order → shipment */}
          {shipments.map((_, i) => {
            const visible = phase >= 1;
            const d = curve(orderRight, shipLeft(i));
            return (
              <path
                key={`os-${i}`}
                d={d}
                fill="none"
                stroke={accent}
                strokeWidth="1.75"
                strokeLinecap="round"
                strokeDasharray="600"
                strokeDashoffset={visible ? 0 : 600}
                style={{ transition: `stroke-dashoffset 0.7s ease ${i * 0.12}s, opacity 0.3s`, opacity: visible ? 1 : 0 }}
              />
            );
          })}

          {/* shipment → invoice */}
          {shipments.map((_, i) => {
            const visible = phase >= 2;
            const d = curve(shipRight(i), invLeft(i));
            return (
              <path
                key={`si-${i}`}
                d={d}
                fill="none"
                stroke={accent}
                strokeWidth="1.75"
                strokeLinecap="round"
                strokeDasharray="500"
                strokeDashoffset={visible ? 0 : 500}
                style={{ transition: `stroke-dashoffset 0.6s ease ${i * 0.1}s, opacity 0.3s`, opacity: visible ? 1 : 0 }}
              />
            );
          })}
        </svg>

        {/* Order card */}
        <div style={{
          position: 'absolute',
          left: orderX, top: orderY,
          width: CARD_W, height: CARD_H,
          background: paper, border: `1px solid ${line}`,
          borderRadius: radius,
          padding: '16px 18px',
          fontFamily: display, color: ink,
          boxSizing: 'border-box',
          boxShadow: t.shadow || '0 1px 2px rgba(0,0,0,0.04)',
        }}>
          <div style={{ fontFamily: mono, fontSize: 10.5, color: label, letterSpacing: '0.06em', marginBottom: 6 }}>ORDER #1042</div>
          <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>$338.50</div>
          <div style={{ fontSize: 13, color: muted, marginTop: 2 }}>6 items · tax + shipping</div>
          <div style={{ marginTop: 10, height: 1, background: line }} />
          <div style={{ fontFamily: mono, fontSize: 11, color: muted, marginTop: 8, display: 'flex', justifyContent: 'space-between' }}>
            <span>1 invoice</span>
            <span style={{ color: t.warnColor || '#c14a3a' }}>↻ ships in parts</span>
          </div>
        </div>

        {/* Shipment cards */}
        {shipments.map((s, i) => {
          const visible = phase >= 1;
          return (
            <div key={s.id} style={{
              position: 'absolute',
              left: shipX, top: shipY(i),
              width: CARD_W, height: CARD_H,
              background: paper, border: `1px solid ${line}`,
              borderRadius: radius,
              padding: '16px 18px',
              fontFamily: display, color: ink,
              boxSizing: 'border-box',
              transform: visible ? 'translateX(0)' : 'translateX(-18px)',
              opacity: visible ? 1 : 0,
              transition: `all 0.45s cubic-bezier(.2,.7,.3,1) ${i * 0.12}s`,
              boxShadow: t.shadow || '0 1px 2px rgba(0,0,0,0.04)',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
                <div style={{ fontFamily: mono, fontSize: 10, color: label, letterSpacing: '0.06em', whiteSpace: 'nowrap' }}>SHIP · {s.id}</div>
                <div style={{ fontFamily: mono, fontSize: 10, color: muted, whiteSpace: 'nowrap' }}>{s.weight}</div>
              </div>
              <div style={{ fontSize: 16, fontWeight: 500, marginTop: 10 }}>{s.items}</div>
              <div style={{ fontSize: 12.5, color: muted, marginTop: 4 }}>fulfilled · tracking ready</div>
            </div>
          );
        })}

        {/* Invoice cards */}
        {shipments.map((s, i) => {
          const visible = phase >= 2;
          const settled = phase >= 3;
          return (
            <div key={`inv-${s.id}`} style={{
              position: 'absolute',
              left: invX, top: invY(i),
              width: CARD_W, height: CARD_H,
              background: paper,
              border: `1px solid ${settled ? accent : line}`,
              borderRadius: radius,
              padding: '16px 18px',
              fontFamily: display, color: ink,
              boxSizing: 'border-box',
              transform: visible ? 'translateX(0)' : 'translateX(18px)',
              opacity: visible ? 1 : 0,
              transition: `all 0.5s cubic-bezier(.2,.7,.3,1) ${i * 0.12}s`,
              boxShadow: settled ? `0 0 0 3px ${accentSoft}` : (t.shadow || '0 1px 2px rgba(0,0,0,0.04)'),
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
                <div style={{ fontFamily: mono, fontSize: 10, color: label, letterSpacing: '0.06em', whiteSpace: 'nowrap' }}>
                  INV-1042-{i+1}
                </div>
                {s.final && (
                  <div style={{
                    fontFamily: mono, fontSize: 9.5, letterSpacing: '0.1em',
                    color: accent, background: accentSoft,
                    padding: '2px 6px', borderRadius: 3,
                  }}>FINAL</div>
                )}
              </div>
              <div style={{ fontSize: 20, fontWeight: 600, marginTop: 8, letterSpacing: '-0.01em' }}>{s.total}</div>
              <div style={{ fontSize: 12.5, color: muted, marginTop: 2 }}>reconciled · tax allocated</div>
            </div>
          );
        })}

        {/* Reconcile tag */}
        <div style={{
          position: 'absolute',
          right: PAD_X,
          bottom: 6,
          fontFamily: mono,
          fontSize: 11,
          color: accent,
          opacity: phase >= 3 ? 1 : 0,
          transition: 'opacity 0.4s ease',
        }}>
          Σ $338.50 ✓ penny-accurate
        </div>
      </div>
    </div>
  );
}

window.ShipmentDiagram = ShipmentDiagram;
