// Live demo preview — a looping animation that simulates Estimado AI
// generating an estimate. Stand-in for the eventual product GIF.
// Designed to live in the "media slot" above the form.
//
// Composition:
//   - browser-window-ish frame with mono header (filename + live dot)
//   - source chips on the left (blueprint, photos, video, voice memo)
//   - "Generating…" panel on the right with line items appearing one by one
//   - subtle progress bar at the bottom
//
// All proportions scale via the container width; pass `compact` for mobile.

const LINE_ITEMS = [
  ['Demolition — kitchen',                '$3,420'],
  ['Cabinetry — shaker, full overlay',    '$18,750'],
  ['Quartz countertop (32 sqft)',         '$4,160'],
  ['Subway tile backsplash',              '$1,280'],
  ['Electrical — 6 circuits, rough+trim', '$2,940'],
  ['Plumbing rough-in + fixtures',        '$3,610'],
  ['LVP flooring (240 sqft)',             '$2,184'],
  ['Paint — walls + ceiling + trim',      '$1,840'],
];

const SOURCES = [
  { label: 'blueprint.pdf',    kind: 'pdf'   },
  { label: 'walkthrough.mp4',  kind: 'video' },
  { label: 'jobsite-photos',   kind: 'image' },
  { label: 'voice-memo.m4a',   kind: 'audio' },
];

function SourceIcon({ kind, size = 14 }) {
  if (kind === 'pdf') {
    return (
      <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
        <rect x="2.5" y="1.5" width="9" height="11" rx="1.2" stroke="currentColor" strokeWidth="1.1"/>
        <path d="M4.5 4.5h5M4.5 6.5h5M4.5 8.5h3" stroke="currentColor" strokeWidth="1.1" strokeLinecap="round"/>
      </svg>
    );
  }
  if (kind === 'video') {
    return (
      <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
        <rect x="1.5" y="3" width="8" height="8" rx="1.2" stroke="currentColor" strokeWidth="1.1"/>
        <path d="M9.5 5.5L12.5 4v6L9.5 8.5" stroke="currentColor" strokeWidth="1.1" strokeLinejoin="round"/>
      </svg>
    );
  }
  if (kind === 'image') {
    return (
      <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
        <rect x="1.5" y="2.5" width="11" height="9" rx="1.2" stroke="currentColor" strokeWidth="1.1"/>
        <path d="M1.5 9.5l3.5-3 3 2.5 1.5-1.5 3 2.5" stroke="currentColor" strokeWidth="1.1" strokeLinejoin="round"/>
        <circle cx="4.5" cy="5.5" r="0.9" fill="currentColor"/>
      </svg>
    );
  }
  // audio
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M3 5v4M5.5 3v8M8 5v4M10.5 6v2" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
    </svg>
  );
}

function LiveDemo({ compact = false }) {
  const [tick, setTick] = React.useState(0);
  // Show fewer items in compact mode so the panel doesn't dominate the mobile fold
  const ITEMS = compact ? LINE_ITEMS.slice(0, 5) : LINE_ITEMS;
  const cycleLen = ITEMS.length + 2; // +2 hold frames at the end

  React.useEffect(() => {
    const id = setInterval(() => setTick((t) => (t + 1) % cycleLen), compact ? 600 : 700);
    return () => clearInterval(id);
  }, [cycleLen, compact]);

  const visibleItems = ITEMS.slice(0, Math.min(tick, ITEMS.length));
  const progress = Math.min(1, tick / ITEMS.length);
  const isDone = tick >= ITEMS.length;

  // Show source chips lighting up sequentially in the first 4 ticks
  const sourcesActive = SOURCES.map((_, i) => tick >= i + 1 || isDone);

  const total = visibleItems.reduce((s, [, p]) => {
    const n = Number(p.replace(/[^0-9.]/g, ''));
    return s + (isNaN(n) ? 0 : n);
  }, 0);

  const fmt = (n) => '$' + n.toLocaleString('en-US');

  // ── Layout knobs ─────────────────────────────
  const pad      = compact ? 10 : 14;
  const headerH  = compact ? 24 : 30;
  const labelFS  = compact ? 9.5 : 10.5;
  const itemFS   = compact ? 11 : 12;
  const headFS   = compact ? 10.5 : 11.5;
  const totalFS  = compact ? 14 : 16;
  const cornerR  = compact ? 12 : 14;

  return (
    <div style={{
      width: '100%',
      background: C.ink,
      borderRadius: cornerR,
      overflow: 'hidden',
      boxShadow: '0 24px 60px -30px rgba(21,20,15,0.45), 0 1px 0 rgba(255,255,255,0.04) inset',
      border: `1px solid #2A2822`,
      color: C.paper,
      fontFamily: F.ui,
    }}>
      {/* App chrome */}
      <div style={{
        height: headerH, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: `0 ${pad}px`,
        borderBottom: '1px solid rgba(255,255,255,0.08)',
        background: 'rgba(255,255,255,0.02)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 7, height: 7, borderRadius: 999, background: 'rgba(255,255,255,0.18)' }} />
          <span style={{ width: 7, height: 7, borderRadius: 999, background: 'rgba(255,255,255,0.18)' }} />
          <span style={{ width: 7, height: 7, borderRadius: 999, background: 'rgba(255,255,255,0.18)' }} />
        </div>
        <span style={{
          fontFamily: F.mono, fontSize: labelFS,
          color: 'rgba(250,248,243,0.55)', letterSpacing: '0.08em', textTransform: 'uppercase',
        }}>
          estimado · new estimate
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span className="om-pulse-dot" style={{ width: 6, height: 6 }} />
          <span style={{
            fontFamily: F.mono, fontSize: labelFS,
            color: 'rgba(250,248,243,0.7)', letterSpacing: '0.08em', textTransform: 'uppercase',
          }}>{isDone ? 'done' : 'live'}</span>
        </span>
      </div>

      {/* Two-column body */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: compact ? '90px 1fr' : '124px 1fr',
        minHeight: compact ? 142 : 232,
      }}>
        {/* Sources column */}
        <div style={{
          background: 'rgba(255,255,255,0.02)',
          borderRight: '1px solid rgba(255,255,255,0.06)',
          padding: `${pad}px ${pad - 2}px`,
          display: 'flex', flexDirection: 'column', gap: compact ? 6 : 8,
        }}>
          <div style={{
            fontFamily: F.mono, fontSize: labelFS,
            color: 'rgba(250,248,243,0.45)', letterSpacing: '0.1em',
            textTransform: 'uppercase', marginBottom: 2,
          }}>Inputs</div>
          {SOURCES.map((s, i) => {
            const active = sourcesActive[i];
            return (
              <div key={s.label} style={{
                display: 'flex', alignItems: 'center', gap: 8,
                padding: compact ? '5px 7px' : '7px 9px',
                borderRadius: 8,
                background: active ? 'rgba(250,248,243,0.07)' : 'transparent',
                border: `1px solid ${active ? 'rgba(250,248,243,0.14)' : 'rgba(250,248,243,0.06)'}`,
                color: active ? C.paper : 'rgba(250,248,243,0.45)',
                transition: 'all 0.3s ease',
                fontSize: compact ? 10.5 : 11.5,
                fontFamily: F.ui,
              }}>
                <SourceIcon kind={s.kind} size={compact ? 11 : 13} />
                <span style={{
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  letterSpacing: '-0.005em',
                }}>{s.label}</span>
              </div>
            );
          })}
        </div>

        {/* Output column */}
        <div style={{
          padding: `${pad}px ${pad}px ${pad}px ${pad + 2}px`,
          display: 'flex', flexDirection: 'column',
          minWidth: 0,
        }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            marginBottom: compact ? 6 : 8,
          }}>
            <div style={{
              fontFamily: F.mono, fontSize: labelFS,
              color: 'rgba(250,248,243,0.45)', letterSpacing: '0.1em', textTransform: 'uppercase',
            }}>Estimate · #E-2041</div>
            <div style={{
              fontFamily: F.mono, fontSize: labelFS,
              color: 'rgba(250,248,243,0.45)', letterSpacing: '0.08em', textTransform: 'uppercase',
            }}>{Math.round(progress * 100)}%</div>
          </div>

          {/* Line items */}
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: compact ? 4 : 5, minHeight: 0 }}>
            {visibleItems.map(([label, price], i) => (
              <div key={label} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                gap: 8,
                fontSize: itemFS, color: 'rgba(250,248,243,0.92)',
                opacity: 0, animation: 'ld-fade-in 0.35s ease forwards',
                animationDelay: '0s',
              }}>
                <span style={{
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  letterSpacing: '-0.005em',
                }}>{label}</span>
                <span style={{
                  fontFamily: F.mono, fontSize: itemFS - 0.5,
                  color: 'rgba(250,248,243,0.78)', whiteSpace: 'nowrap',
                }}>{price}</span>
              </div>
            ))}
            {/* Empty filler lines */}
            {Array.from({ length: Math.max(0, ITEMS.length - visibleItems.length) }).map((_, i) => (
              <div key={`f-${i}`} style={{
                display: 'flex', justifyContent: 'space-between', gap: 8,
                fontSize: itemFS,
              }}>
                <span style={{
                  height: 8, borderRadius: 3,
                  background: 'rgba(250,248,243,0.06)',
                  flex: i % 2 === 0 ? 0.7 : 0.55,
                }} />
                <span style={{
                  height: 8, width: 36, borderRadius: 3,
                  background: 'rgba(250,248,243,0.06)',
                }} />
              </div>
            ))}
          </div>

          {/* Total */}
          <div style={{
            marginTop: compact ? 8 : 10,
            paddingTop: compact ? 7 : 9,
            borderTop: '1px solid rgba(250,248,243,0.12)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          }}>
            <span style={{
              fontFamily: F.mono, fontSize: labelFS,
              color: 'rgba(250,248,243,0.55)', letterSpacing: '0.1em', textTransform: 'uppercase',
            }}>Total</span>
            <span style={{
              fontFamily: F.display, fontSize: totalFS, fontWeight: 460,
              letterSpacing: '-0.018em', color: C.paper,
            }}>{fmt(total)}</span>
          </div>
        </div>
      </div>

      {/* Progress bar at bottom */}
      <div style={{ height: 2, background: 'rgba(250,248,243,0.06)' }}>
        <div style={{
          height: '100%',
          width: `${progress * 100}%`,
          background: C.paper,
          transition: 'width 0.6s ease',
        }} />
      </div>
    </div>
  );
}

window.LiveDemo = LiveDemo;
