// Live Estimado demo — combined multi-input.
// Shows blueprint + photos/video + voice note being processed together (which is
// how the product actually works). One continuous cycle, no input switching.

const LD_LINES = [
  { no: '1.1', name: 'Porcelain Floor Tile 6"x24"',    qty: '550 SF',  cost: '$3,217.50' },
  { no: '1.2', name: 'Modified Thinset Mortar',        qty: '8 Bag',   cost: '$259.79'   },
  { no: '1.3', name: 'Floor Tile Installation Labor',  qty: '9 HRS',   cost: '$1,099.80' },
  { no: '2.1', name: 'Ceiling paint, two coats',       qty: '8,240 SF',cost: '$15,244.00'},
  { no: '3.1', name: 'Reception millwork package',     qty: '1 LS',    cost: '$42,600.00'},
];

// Timeline (each tick = 700ms):
//  0      uploads + transcript animate in
//  1      "Reading plans" lights up
//  2      "Understanding pictures" lights up
//  3      "Transcribing voice note" lights up
//  4      "Classifying trades"
//  5      "Extracting quantities"
//  6      "Pricing materials"
//  7..11  line items reveal one by one
//  12     total appears
//  13..16 hold then reset
const LD_TOTAL_TICKS = 17;

function LiveDemo({ compact = false } = {}) {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 700);
    return () => clearInterval(id);
  }, []);
  const cycle = tick % LD_TOTAL_TICKS;

  const READING_STEPS = [
    { label: 'Reading plans',           detail: '3 pages · 8 sheets' },
    { label: 'Understanding pictures',  detail: 'Site conditions identified' },
    { label: 'Transcribing voice note', detail: '142 words · 2 rooms' },
  ];
  const REASONING_STEPS = [
    { label: 'Classifying trades',      detail: 'Flooring · Painting · Millwork' },
    { label: 'Extracting quantities',   detail: '550 SF · 8,240 SF · 1 LS' },
    { label: 'Pricing materials',       detail: 'Home Depot · regional' },
  ];

  return (
    <div style={{
      borderRadius: 16, overflow: 'hidden',
      background: C.paper, border: `1px solid ${C.rule}`,
      boxShadow: '0 30px 80px -40px rgba(21,20,15,0.4), 0 8px 24px -12px rgba(21,20,15,0.14)',
      fontFamily: F.ui,
      display: 'flex', flexDirection: 'column',
      width: '100%',
    }}>
      {/* Window chrome */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 14px', background: C.paper2,
        borderBottom: `1px solid ${C.rule}`, flexShrink: 0,
      }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <span style={{ width: 10, height: 10, borderRadius: 999, background: '#e5e0d5' }} />
          <span style={{ width: 10, height: 10, borderRadius: 999, background: '#e5e0d5' }} />
          <span style={{ width: 10, height: 10, borderRadius: 999, background: '#e5e0d5' }} />
        </div>
        <div style={{ flex: 1, textAlign: 'center', fontFamily: F.mono, fontSize: compact ? 10 : 11, color: C.muted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {compact ? 'New estimate' : 'estimado.com · new estimate · Harbor Lobby Refresh'}
        </div>
        <span style={{ width: 40 }} />
      </div>

      {/* Inputs row + transcript */}
      <div style={{ padding: compact ? '14px 14px 12px' : '18px 20px 14px', borderBottom: `1px solid ${C.rule}`, flexShrink: 0 }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          marginBottom: 12, gap: 8,
        }}>
          <span style={{
            fontFamily: F.mono,
            fontSize: compact ? 9 : 11,
            letterSpacing: compact ? '0.08em' : '0.14em',
            textTransform: 'uppercase',
            color: C.muted,
            whiteSpace: 'nowrap',
          }}>Inputs · 3 sources received</span>
          <span style={{
            padding: compact ? '2px 7px' : '3px 9px', borderRadius: 999,
            background: C.paper, border: `1px solid ${C.rule}`, color: C.ink2,
            fontFamily: F.mono, fontSize: compact ? 8.5 : 10,
            letterSpacing: compact ? '0.06em' : '0.08em', textTransform: 'uppercase',
            whiteSpace: 'nowrap', flexShrink: 0,
          }}>Processing all</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: compact ? '1fr' : 'repeat(3, 1fr)', gap: 10 }}>
          <InputCardPDF delay={0} compact={compact} />
          <InputCardPhotos delay={120} compact={compact} />
          <InputCardVoice delay={240} cycle={cycle} compact={compact} />
        </div>
        <TranscriptStrip cycle={cycle} compact={compact} />
      </div>

      {/* Reasoning */}
      <div style={{ padding: '14px 20px', display: 'flex', flexDirection: 'column', gap: 4 }}>
        {READING_STEPS.map((s, i) => (
          <StepRow key={i} visible={cycle >= i + 1} active={cycle === i + 1} label={s.label} detail={compact ? null : s.detail} compact={compact} />
        ))}
        <div style={{ height: 1, background: C.rule, margin: '8px 0' }} />
        {REASONING_STEPS.map((s, i) => (
          <StepRow key={i + 10} visible={cycle >= i + 4} active={cycle === i + 4} label={s.label} detail={compact ? null : s.detail} compact={compact} />
        ))}
      </div>

      {/* Line items + total */}
      <div style={{ padding: '4px 20px 18px' }}>
        <LineItems items={LD_LINES} cycle={cycle} startAt={7} compact={compact} />
        <div style={{ height: 12 }} />
        <TotalRow visible={cycle >= 12} script={{ label: 'Estimate total', value: '$148,900' }} />
      </div>
    </div>
  );
}

// ─────────── INPUT CARDS ───────────
function InputCardPDF({ delay = 0, compact = false }) {
  return (
    <InputCardShell delay={delay} compact={compact} icon={<PdfBadge compact={compact} />} title="Harbor_Lobby_A2.1.pdf" meta="3 pages · 2.4 MB" tag="Blueprint" />
  );
}

function InputCardPhotos({ delay = 0, compact = false }) {
  // Real project photos (renovation reference shots): lobby reception,
  // tile floor sample, ceiling/lights, lobby seating. The 5th is the
  // blurred "stack" peek behind the +5 tile.
  const photos = [
    'assets/lobby-1.jpg',
    'assets/lobby-2.jpg',
    'assets/lobby-3.jpg',
    'assets/lobby-4.jpg',
  ];
  const peek = 'assets/lobby-peek.jpg';
  const thumbW = compact ? 16 : 20;
  const thumbH = compact ? 20 : 26;
  return (
    <div style={{
      ...inputCardStyle(compact),
      animation: `cardIn 0.4s ease ${delay}ms both`,
    }}>
      <div style={inputCardHeader}>
        <div style={{ display: 'flex', gap: 3 }}>
          {photos.map((src, i) => (
            <div key={i} style={{
              width: thumbW, height: thumbH, borderRadius: 3,
              background: '#3a342a',
              position: 'relative', overflow: 'hidden',
              boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.08)',
            }}>
              <img src={src} alt="" loading="lazy" style={{
                position: 'absolute', inset: 0,
                width: '100%', height: '100%',
                objectFit: 'cover', display: 'block',
              }} />
            </div>
          ))}
          <div style={{
            position: 'relative',
            width: thumbW + 2, height: thumbH, borderRadius: 3,
            overflow: 'hidden',
            background: C.ink,
          }}>
            <img src={peek} alt="" loading="lazy" style={{
              position: 'absolute', inset: 0,
              width: '100%', height: '100%',
              objectFit: 'cover',
              filter: 'blur(2.5px) brightness(0.55)',
              transform: 'scale(1.15)',
            }} />
            <div style={{
              position: 'absolute', inset: 0,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              color: C.paper,
              fontFamily: F.mono, fontSize: 9, fontWeight: 500,
              textShadow: '0 1px 2px rgba(0,0,0,0.5)',
            }}>+5</div>
          </div>
        </div>
        <div style={inputCardMeta}>
          <div style={inputCardTitle}>8 photos + 1 video</div>
          <div style={inputCardSubtitle}>Lobby walk-through · 24.7 MB</div>
        </div>
      </div>
      {!compact && <div style={inputCardTag}>Photos + Video</div>}
    </div>
  );
}

function InputCardVoice({ delay = 0, cycle, compact = false }) {
  const active = cycle <= 3;
  return (
    <div style={{
      ...inputCardStyle(compact),
      animation: `cardIn 0.4s ease ${delay}ms both`,
    }}>
      <div style={inputCardHeader}>
        <Waveform active={active} bars={compact ? 9 : 11} />
        <div style={inputCardMeta}>
          <div style={inputCardTitle}>Walk-through.m4a</div>
          <div style={inputCardSubtitle}>1:42 · voice memo</div>
        </div>
      </div>
      {!compact && <div style={inputCardTag}>Voice note</div>}
    </div>
  );
}

function InputCardShell({ icon, title, meta, tag, delay = 0, compact = false }) {
  return (
    <div style={{
      ...inputCardStyle(compact),
      animation: `cardIn 0.4s ease ${delay}ms both`,
    }}>
      <div style={inputCardHeader}>
        {icon}
        <div style={inputCardMeta}>
          <div style={inputCardTitle}>{title}</div>
          <div style={inputCardSubtitle}>{meta}</div>
        </div>
      </div>
      {!compact && <div style={inputCardTag}>{tag}</div>}
    </div>
  );
}

const inputCardStyle = (compact = false) => ({
  display: 'flex', flexDirection: 'column',
  border: `1px solid ${C.rule}`, borderRadius: 10,
  background: C.paper2,
  padding: compact ? '8px 10px' : '8px 11px',
  position: 'relative',
  minHeight: 0,
  justifyContent: 'space-between',
});
const inputCardHeader = { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 0 };
const inputCardMeta = { flex: 1, minWidth: 0 };
const inputCardTitle = { fontSize: 12.5, fontWeight: 500, color: C.ink, lineHeight: 1.25, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };
const inputCardSubtitle = { fontFamily: 'Geist Mono, ui-monospace, monospace', fontSize: 10.5, color: C.muted, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };
const inputCardTag = {
  fontFamily: 'Geist Mono, ui-monospace, monospace', fontSize: 9.5,
  letterSpacing: '0.12em', textTransform: 'uppercase',
  color: C.muted, marginTop: 6,
};

function PdfBadge({ compact = false }) {
  const sz = compact ? 28 : 32;
  // Document shape with folded corner + "PDF" label band, in ink on paper.
  return (
    <div style={{
      width: sz, height: sz,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
    }}>
      <svg width={sz} height={sz} viewBox="0 0 32 32" fill="none" aria-hidden="true">
        {/* Page body with folded corner — single path so the corner is a cut, not an overlay */}
        <path
          d="M5 2 H20 L27 9 V28 A2 2 0 0 1 25 30 H7 A2 2 0 0 1 5 28 Z"
          fill={C.paper}
          stroke={C.ink}
          strokeWidth="1.6"
          strokeLinejoin="round"
        />
        {/* Folded-corner triangle */}
        <path
          d="M20 2 V9 H27 Z"
          fill={C.ink}
        />
        {/* PDF label band */}
        <rect x="5" y="15" width="22" height="9" fill={C.ink} />
        <text
          x="16" y="22"
          textAnchor="middle"
          fill={C.paper}
          fontFamily="Geist Mono, ui-monospace, monospace"
          fontSize="6.5"
          fontWeight="700"
          letterSpacing="0.5"
        >PDF</text>
      </svg>
    </div>
  );
}

// Inject the upload-card pop-in keyframe once
if (typeof document !== 'undefined' && !document.getElementById('ld-keyframes')) {
  const s = document.createElement('style');
  s.id = 'ld-keyframes';
  s.textContent = `
    @keyframes cardIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
    @keyframes transcriptCaret { 50% { opacity: 0; } }
  `;
  document.head.appendChild(s);
}

// ─────────── TRANSCRIPT STRIP (under inputs) ───────────
function TranscriptStrip({ cycle, compact = false }) {
  const full = '"Need to redo the lobby — porcelain tile floor, ceiling paint two coats, and that reception millwork piece. Also check the ceiling lights, the existing fixtures are shot."';
  // Reveal over ticks 0..3 (4 ticks of typing while the reading steps light up)
  const progress = Math.min(1, Math.max(0, cycle / 3));
  const shown = full.slice(0, Math.floor(full.length * progress));
  return (
    <div style={{
      marginTop: 10, padding: '8px 12px',
      background: 'rgba(21,20,15,0.04)',
      border: `1px dashed ${C.rule}`, borderRadius: 8,
      fontFamily: F.mono, fontSize: 11, color: C.ink2,
      // Fixed size so the box doesn't grow as text types in.
      // Sized to fit the full transcript at each breakpoint.
      height: compact ? 100 : 60,
      lineHeight: 1.5,
      overflow: 'hidden',
    }}>
      <span style={{
        fontFamily: F.mono, fontSize: 9.5, letterSpacing: '0.14em',
        color: C.muted, textTransform: 'uppercase', marginRight: 8,
      }}>Transcript</span>
      {shown}
      {progress < 1 && (
        <span style={{
          display: 'inline-block', width: 1.5, height: 12,
          background: C.muted, marginLeft: 2, transform: 'translateY(2px)',
          animation: 'transcriptCaret 0.9s steps(1) infinite',
        }} />
      )}
    </div>
  );
}

function Waveform({ active = true, bars = 14 }) {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    if (!active) return;
    const id = setInterval(() => setT((x) => x + 1), 150);
    return () => clearInterval(id);
  }, [active]);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 2, height: 32, width: 60, flexShrink: 0 }}>
      {Array.from({ length: bars }).map((_, i) => {
        const base = 3 + Math.abs(Math.sin((i + 1) * 1.2)) * 16;
        const phased = active ? base + Math.abs(Math.sin(i + t * 0.6)) * 8 : base * 0.55;
        return (
          <span key={i} style={{
            width: 2.5, height: phased, borderRadius: 2,
            background: active ? C.ink : C.muted,
            transition: 'height 0.15s ease',
          }} />
        );
      })}
    </div>
  );
}

// ─────────── REASONING STEP ROW ───────────
function StepRow({ visible, active, label, detail }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '5px 4px',
      opacity: visible ? 1 : 0.28,
      transition: 'opacity 0.3s ease',
    }}>
      <span style={{
        width: 14, height: 14, borderRadius: 999,
        border: `1.5px solid ${visible ? C.ink : C.rule}`,
        background: visible ? C.ink : 'transparent',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        {visible && (
          <svg width="8" height="8" viewBox="0 0 8 8" fill="none">
            <path d="M1.5 4.2L3.3 6L6.5 2.5" stroke={C.paper} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        )}
      </span>
      <span style={{ fontSize: 13.5, color: visible ? C.ink : C.muted, fontWeight: 450 }}>
        {label}{active && <Dots />}
      </span>
      {detail && visible && (
        <span style={{ fontFamily: F.mono, fontSize: 11, color: C.muted, marginLeft: 'auto' }}>{detail}</span>
      )}
    </div>
  );
}

function Dots() {
  const [n, setN] = React.useState(1);
  React.useEffect(() => {
    const id = setInterval(() => setN((x) => x % 3 + 1), 280);
    return () => clearInterval(id);
  }, []);
  return <span style={{ display: 'inline-block', minWidth: 18, color: C.muted }}>{'.'.repeat(n)}</span>;
}

function LineItems({ items, cycle, startAt, compact = false }) {
  const cols = compact ? '1fr 78px' : '32px 1fr 88px 90px';
  return (
    <div style={{ border: `1px solid ${C.rule}`, borderRadius: 10, overflow: 'hidden' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: cols,
        padding: '10px 14px', background: C.paper2, borderBottom: `1px solid ${C.rule}`,
        fontFamily: F.mono, fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: C.muted,
        gap: 12,
      }}>
        {!compact && <span>#</span>}
        <span>Item</span>
        {!compact && <span>Qty</span>}
        <span style={{ textAlign: 'right' }}>Total</span>
      </div>
      {items.map((it, i) => {
        const visible = cycle >= startAt + i;
        return (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: cols,
            padding: '9px 14px', gap: 12, alignItems: 'center',
            borderBottom: i < items.length - 1 ? `1px solid ${C.rule}` : 'none',
            opacity: visible ? 1 : 0, transform: visible ? 'translateY(0)' : 'translateY(4px)',
            transition: 'opacity 0.3s ease, transform 0.3s ease',
            background: C.paper,
          }}>
            {!compact && <span style={{ fontFamily: F.mono, fontSize: 11, color: C.muted }}>{it.no}</span>}
            <span style={{ fontSize: compact ? 12 : 13, color: C.ink, lineHeight: 1.3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.name}</span>
            {!compact && <span style={{ fontFamily: F.mono, fontSize: 11.5, color: C.ink2 }}>{it.qty}</span>}
            <span style={{ fontFamily: F.mono, fontSize: compact ? 11.5 : 12.5, color: C.ink, textAlign: 'right', fontWeight: 500 }}>{it.cost}</span>
          </div>
        );
      })}
    </div>
  );
}

function TotalRow({ visible, script }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '14px 18px', background: C.ink, color: C.paper, borderRadius: 10,
      opacity: visible ? 1 : 0, transform: visible ? 'translateY(0)' : 'translateY(6px)',
      transition: 'opacity 0.3s ease, transform 0.3s ease',
    }}>
      <span style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(250,248,243,0.55)' }}>
        {script.label}
      </span>
      <span style={{ fontFamily: F.display, fontWeight: 400, fontSize: 30, letterSpacing: '-0.02em' }}>
        {script.value}
      </span>
    </div>
  );
}

Object.assign(window, { LiveDemo });
