// AI Quote Generator - the killer feature screen

function AIQuote({ state, setState }) {
  const trade = TRADES[state.tradeId];
  const job = FOCUS_JOB[state.tradeId];
  const stream = QUOTE_STREAMS[state.tradeId];

  const [phase, setPhase] = React.useState('ready'); // ready | generating | clarifying | clarified | complete
  const [visibleItems, setVisibleItems] = React.useState([]);
  const [clarifyingAnswer, setClarifyingAnswer] = React.useState(null); // 'yes' | 'no' | null
  const [notes, setNotes] = React.useState(job.notes);
  const [editing, setEditing] = React.useState(null); // index of item being edited
  const [removedIdx, setRemovedIdx] = React.useState(new Set());

  // Stream in items
  React.useEffect(() => {
    if (phase !== 'generating') return;
    let cancelled = false;
    let idx = 0;
    const tick = () => {
      if (cancelled) return;
      if (idx >= stream.items.length) {
        // Show clarifying question after all items
        setTimeout(() => !cancelled && setPhase('clarifying'), 400);
        return;
      }
      const item = stream.items[idx];
      setTimeout(() => {
        if (cancelled) return;
        setVisibleItems(v => [...v, item]);
        idx++;
        tick();
      }, item.delay || 800);
    };
    tick();
    return () => { cancelled = true; };
  }, [phase]);

  const start = () => {
    setVisibleItems([]);
    setClarifyingAnswer(null);
    setRemovedIdx(new Set());
    setPhase('generating');
  };

  const answer = (a) => {
    setClarifyingAnswer(a);
    if (a === 'yes') {
      setTimeout(() => setVisibleItems(v => [...v, { ...stream.clarifyingLine, added: true }]), 350);
    }
    setTimeout(() => setPhase('complete'), 900);
  };

  const allItems = visibleItems.filter((_, i) => !removedIdx.has(i));
  const subtotal = allItems.reduce((a, it) => a + (it.total || 0), 0);
  const gst = Math.round(subtotal * 0.1 * 100) / 100;
  const total = Math.round((subtotal + gst) * 100) / 100;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '440px 1fr', height: 'calc(100vh - 52px)', minHeight: 0 }}>
      {/* LEFT - inputs */}
      <div style={{
        borderRight: '1px solid var(--border)', overflowY: 'auto',
        padding: '22px 22px 60px', background: 'var(--surface-2)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
          <Chip tone="accent">{job.id}</Chip>
          <Chip tone="ghost">{trade.label}</Chip>
          <Chip tone="neutral" icon="map">{job.address.split(',')[0]}</Chip>
        </div>
        <h1 style={{ fontSize: 22, fontWeight: 500, letterSpacing: -0.4, margin: '10px 0 4px', fontFamily: 'var(--display)', textWrap: 'balance' }}>
          {job.title}
        </h1>
        <div style={{ fontSize: 13, color: 'var(--ink-60)', marginBottom: 20 }}>
          {job.customer} · {job.customerPhone}
        </div>

        <Section label="Job description">
          <div style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--ink-80)' }}>{job.description}</div>
        </Section>

        <Section label={`Site-visit photos (${job.photos.length})`} right={<button style={microBtn}><Icon name="plus" size={11}/> add</button>}>
          <div data-tour="photos" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {job.photos.map((p, i) => (
              <div key={i}>
                <PlaceholderImage label={p.label} tone={p.tone} height={96} />
                <div style={{ fontSize: 10.5, color: 'var(--ink-60)', fontFamily: 'var(--mono)', marginTop: 4, lineHeight: 1.35 }}>{p.caption}</div>
              </div>
            ))}
          </div>
        </Section>

        <Section label="Voice note" right={<span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-60)' }}>{job.voiceNote}</span>}>
          <div data-tour="voice" style={{
            padding: 10, border: '1px solid var(--border)', borderRadius: 8,
            background: 'var(--surface)', display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <button style={{
              width: 28, height: 28, borderRadius: 14, border: 'none',
              background: 'var(--ink)', color: 'var(--paper)', cursor: 'pointer',
              display: 'grid', placeItems: 'center',
            }}><Icon name="play" size={11}/></button>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 2, height: 22 }}>
              {Array.from({ length: 32 }).map((_, i) => {
                const h = 6 + Math.abs(Math.sin(i * 0.7 + i * i * 0.1)) * 14;
                return <div key={i} style={{ width: 2, height: h, background: i < 6 ? 'var(--ink-70)' : 'var(--ink-30)', borderRadius: 1 }} />;
              })}
            </div>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-60)' }}>0:04</span>
          </div>
          <div style={{ marginTop: 6, fontSize: 11, color: 'var(--ink-60)', fontStyle: 'italic', lineHeight: 1.4 }}>
            Auto-transcribed · used as AI input
          </div>
        </Section>

        <Section label="Tech notes">
          <textarea
            value={notes}
            onChange={e => setNotes(e.target.value)}
            style={{
              width: '100%', minHeight: 110, padding: 10, borderRadius: 8,
              border: '1px solid var(--border)', background: 'var(--surface)',
              fontSize: 13, lineHeight: 1.5, color: 'var(--ink-80)',
              fontFamily: 'var(--sans)', resize: 'vertical', outline: 'none',
              boxSizing: 'border-box',
            }}
          />
        </Section>

        <Section label="Generate">
          <button data-tour="generate" onClick={start} disabled={phase === 'generating' || phase === 'clarifying'}
            style={{
              width: '100%', padding: '14px 16px', borderRadius: 10,
              background: 'var(--ink)', color: 'var(--paper)', border: 'none',
              fontSize: 15, fontWeight: 500, cursor: (phase === 'ready' || phase === 'complete') ? 'pointer' : 'wait',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              boxShadow: '0 2px 0 rgba(20,18,12,0.08), 0 8px 20px -6px rgba(20,18,12,0.25)',
              fontFamily: 'var(--sans)', letterSpacing: -0.2,
              opacity: (phase === 'generating' || phase === 'clarifying') ? 0.7 : 1,
            }}>
            <Icon name="sparkles" size={15}/>
            {phase === 'ready' ? 'Generate with AI' :
             phase === 'generating' ? 'Generating…' :
             phase === 'clarifying' ? 'Waiting for your input' :
             phase === 'complete' ? 'Regenerate' : 'Generate with AI'}
          </button>
          <div style={{ marginTop: 8, fontSize: 11, color: 'var(--ink-60)', textAlign: 'center', fontFamily: 'var(--mono)' }}>
            Reads your photos + notes. Drafts in ~12s. Edit anything.
          </div>
        </Section>
      </div>

      {/* RIGHT - streaming quote */}
      <div style={{ overflowY: 'auto', padding: '22px 28px 60px', minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--ink-60)', letterSpacing: 0.6, textTransform: 'uppercase' }}>Draft quote</div>
            <div style={{ fontSize: 20, fontWeight: 500, letterSpacing: -0.3, marginTop: 4, fontFamily: 'var(--display)' }}>
              Q-{job.id.replace('J-', '')} · {job.customer}
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Btn variant="ghost" size="sm" icon="copy" disabled={phase !== 'complete'}>Copy</Btn>
            <Btn variant="secondary" size="sm" icon="pencil" disabled={phase !== 'complete'}>Edit</Btn>
            <Btn variant="secondary" size="sm" icon="download" disabled={phase !== 'complete'}>PDF</Btn>
            <Btn variant="primary" size="sm" icon="send" iconRight={null} disabled={phase !== 'complete'} onClick={() => setState(s => ({ ...s, screen: 'customer-approval' }))}>
              Send to {job.customer.split(' ')[0]}
            </Btn>
          </div>
        </div>

        {/* Status strip */}
        <div data-tour="status"><StatusStrip phase={phase} preamble={stream.preamble} /></div>

        {/* Item list */}
        <div data-tour="items" style={{
          marginTop: 18, border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden',
          background: 'var(--surface)',
        }}>
          <ItemHeader />
          {visibleItems.map((item, i) => (
            <QuoteLine
              key={i} item={item} idx={i}
              removed={removedIdx.has(i)}
              onRemove={() => setRemovedIdx(new Set([...removedIdx, i]))}
              onRestore={() => { const n = new Set(removedIdx); n.delete(i); setRemovedIdx(n); }}
              onEdit={() => setEditing(i === editing ? null : i)}
              editing={editing === i}
            />
          ))}
          {phase === 'clarifying' && (
            <div data-tour="clarify"><ClarifyingRow q={stream.clarifying} onAnswer={answer} /></div>
          )}
          {clarifyingAnswer && phase !== 'clarifying' && (
            <div style={{ padding: '10px 16px', background: 'var(--accent-tint)', borderBottom: '1px solid var(--border)', fontSize: 12, color: 'var(--accent-ink)', display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="check" size={12}/> {stream.clarifying[clarifyingAnswer]}
            </div>
          )}
          {visibleItems.length === 0 && phase !== 'generating' && phase !== 'clarifying' && (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: 'var(--ink-50)' }}>
              <Icon name="sparkles" size={24} style={{ color: 'var(--ink-40)' }} />
              <div style={{ fontSize: 13, marginTop: 10 }}>Click <strong style={{ color: 'var(--ink)' }}>Generate with AI</strong> to draft line items from the photos + notes.</div>
              <div style={{ fontSize: 11, marginTop: 6, fontFamily: 'var(--mono)' }}>avg 11s · editable · AUD ex-GST</div>
            </div>
          )}
          {phase === 'generating' && visibleItems.length < stream.items.length && <StreamingRow />}

          {/* Totals */}
          {visibleItems.length > 0 && (
            <div data-tour="totals" style={{ borderTop: '1px solid var(--border)', padding: '14px 16px 16px', background: 'var(--surface-2)' }}>
              <Totals subtotal={subtotal} gst={gst} total={total} />
            </div>
          )}
        </div>

        {phase === 'complete' && (
          <div data-tour="send" style={{
            marginTop: 18, padding: '14px 16px', borderRadius: 10,
            background: 'var(--sage-tint)', border: '1px solid var(--sage-border)',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <Icon name="check" size={18} style={{ color: 'var(--sage-ink)' }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--sage-ink)' }}>Quote ready to send.</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-70)', marginTop: 2 }}>14-day acceptance window · GST itemized · includes {trade.licence}</div>
            </div>
            <Btn variant="primary" size="md" icon="send" onClick={() => setState(s => ({ ...s, screen: 'customer-approval' }))}>Send to {job.customer.split(' ')[0]}</Btn>
          </div>
        )}
      </div>
    </div>
  );
}

function Section({ label, children, right }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <div style={{ fontSize: 10.5, color: 'var(--ink-60)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: 0.6 }}>{label}</div>
        {right}
      </div>
      {children}
    </div>
  );
}
const microBtn = { padding: '2px 7px', borderRadius: 5, border: '1px solid var(--border)', background: 'var(--surface)', fontSize: 10.5, color: 'var(--ink-60)', cursor: 'pointer', fontFamily: 'var(--mono)', display: 'inline-flex', alignItems: 'center', gap: 4 };

function StatusStrip({ phase, preamble }) {
  const steps = [
    { id: 'read', label: 'Read photos + notes', done: phase !== 'ready' },
    { id: 'classify', label: 'Classify job · trade match', done: phase !== 'ready' },
    { id: 'draft', label: 'Draft line items', done: phase === 'complete' || phase === 'clarifying', active: phase === 'generating' },
    { id: 'confirm', label: 'Clarify open questions', done: phase === 'complete', active: phase === 'clarifying' },
    { id: 'total', label: 'Sum + GST', done: phase === 'complete' },
  ];
  return (
    <div style={{
      padding: '10px 14px', borderRadius: 10,
      background: 'var(--surface)', border: '1px solid var(--border)',
      display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', fontSize: 12,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink)' }}>
        <span style={{
          width: 7, height: 7, borderRadius: 4,
          background: phase === 'generating' ? 'var(--accent-deep)' : (phase === 'complete' ? 'var(--sage-dark)' : 'var(--ink-40)'),
          boxShadow: phase === 'generating' ? '0 0 0 0 rgba(193,124,46,0.6)' : 'none',
          animation: phase === 'generating' ? 'pulse 1.2s infinite' : 'none',
        }} />
        <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-70)' }}>
          {phase === 'ready' && 'Ready · Claude vision + Australian trades context'}
          {phase === 'generating' && preamble}
          {phase === 'clarifying' && 'One clarifying question before I finalize…'}
          {phase === 'complete' && 'Complete · 11.7s · you have the pen now'}
        </span>
      </div>
      <div style={{ flex: 1 }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        {steps.map((s, i) => (
          <React.Fragment key={s.id}>
            {i > 0 && <div style={{ width: 16, height: 1, background: 'var(--border)' }} />}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 5,
              color: s.done ? 'var(--ink)' : (s.active ? 'var(--accent-deep)' : 'var(--ink-40)'),
              fontSize: 11, fontFamily: 'var(--mono)', letterSpacing: 0.2,
            }}>
              <span style={{
                width: 14, height: 14, borderRadius: 7, border: `1.5px solid currentColor`,
                display: 'grid', placeItems: 'center',
                background: s.done ? 'var(--ink)' : 'transparent',
                color: s.done ? 'var(--paper)' : 'currentColor',
              }}>
                {s.done && <Icon name="check" size={9} strokeWidth={2.5} />}
                {s.active && !s.done && <span style={{ width: 5, height: 5, borderRadius: 3, background: 'currentColor', animation: 'pulse 1s infinite' }} />}
              </span>
              {s.label}
            </div>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

function ItemHeader() {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 80px 90px 110px 40px',
      padding: '10px 16px', background: 'var(--surface-2)', borderBottom: '1px solid var(--border)',
      fontSize: 10, fontFamily: 'var(--mono)', color: 'var(--ink-60)', textTransform: 'uppercase', letterSpacing: 0.6,
      gap: 12,
    }}>
      <div>Line item</div><div style={{ textAlign: 'right' }}>Qty</div><div style={{ textAlign: 'right' }}>Rate AUD</div><div style={{ textAlign: 'right' }}>Total ex-GST</div><div/>
    </div>
  );
}

function QuoteLine({ item, idx, removed, onRemove, onRestore, onEdit, editing }) {
  const [revealed, setRevealed] = React.useState(false);
  React.useEffect(() => { const t = setTimeout(() => setRevealed(true), 30); return () => clearTimeout(t); }, []);
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 80px 90px 110px 40px',
      padding: '10px 16px', borderBottom: '1px solid var(--border)',
      fontSize: 13, gap: 12, alignItems: 'center',
      background: item.added ? 'var(--accent-tint)' : (item.isRebate ? 'var(--sage-tint)' : 'transparent'),
      opacity: revealed ? (removed ? 0.4 : 1) : 0,
      transform: revealed ? 'translateY(0)' : 'translateY(4px)',
      transition: 'opacity 280ms ease, transform 280ms ease, background 300ms',
      textDecoration: removed ? 'line-through' : 'none',
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ color: 'var(--ink)', fontWeight: item.added ? 500 : 400, textWrap: 'pretty' }}>
          {item.text}
          {item.optional && <Chip tone="ghost" style={{ marginLeft: 8, fontSize: 10 }}>optional</Chip>}
          {item.added && <Chip tone="accent" style={{ marginLeft: 8, fontSize: 10 }}>added from Q</Chip>}
        </div>
        {item.note && <div style={{ fontSize: 11, color: 'var(--ink-60)', marginTop: 3 }}>{item.note}</div>}
      </div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 12, textAlign: 'right', color: 'var(--ink-80)' }}>
        {item.qty}{item.unit ? <span style={{ color: 'var(--ink-50)' }}> {item.unit}</span> : ''}
      </div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 12, textAlign: 'right', color: 'var(--ink-80)' }}>
        {item.rate ? fmtAUDcents(item.rate) : '-'}
      </div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 13, textAlign: 'right', color: item.isRebate ? 'var(--sage-ink)' : 'var(--ink)', fontWeight: 500 }}>
        {fmtAUDcents(item.total)}
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        {removed ? (
          <button onClick={onRestore} style={microBtn}>undo</button>
        ) : (
          <button onClick={onRemove} style={{ padding: 4, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--ink-40)', borderRadius: 4 }}
            onMouseEnter={e => e.currentTarget.style.color = 'var(--ink)'}
            onMouseLeave={e => e.currentTarget.style.color = 'var(--ink-40)'}
            title="Remove line"><Icon name="x" size={13}/></button>
        )}
      </div>
    </div>
  );
}

function StreamingRow() {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 80px 90px 110px 40px',
      padding: '10px 16px', borderBottom: '1px solid var(--border)',
      gap: 12, alignItems: 'center',
    }}>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <span style={{ display: 'inline-flex', gap: 3 }}>
          {[0,1,2].map(i => <span key={i} style={{
            width: 5, height: 5, borderRadius: 3, background: 'var(--ink-50)',
            animation: `bounce 1.2s ${i * 0.15}s infinite`,
          }} />)}
        </span>
        <span style={{ fontSize: 12, color: 'var(--ink-60)', fontStyle: 'italic' }}>next line…</span>
      </div>
      <div/><div/><div/><div/>
    </div>
  );
}

function ClarifyingRow({ q, onAnswer }) {
  return (
    <div style={{
      padding: '14px 16px', borderBottom: '1px solid var(--border)',
      background: 'var(--accent-tint)', display: 'flex', gap: 14, alignItems: 'flex-start',
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: 13, background: 'var(--accent-deep)',
        color: 'var(--paper)', display: 'grid', placeItems: 'center', flexShrink: 0,
      }}><Icon name="sparkles" size={12}/></div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 10.5, fontFamily: 'var(--mono)', color: 'var(--accent-ink)', letterSpacing: 0.5, marginBottom: 4, textTransform: 'uppercase' }}>Clarifying question</div>
        <div style={{ fontSize: 13.5, color: 'var(--ink)', lineHeight: 1.5, marginBottom: 12, maxWidth: 640, textWrap: 'pretty' }}>{q.question}</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Btn variant="primary" size="sm" icon="check" onClick={() => onAnswer('yes')}>Yes, add it</Btn>
          <Btn variant="secondary" size="sm" onClick={() => onAnswer('no')}>Skip</Btn>
        </div>
      </div>
    </div>
  );
}

function Totals({ subtotal, gst, total }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-end', fontFamily: 'var(--mono)', fontSize: 13 }}>
      <Row label="Subtotal (ex-GST)" value={fmtAUDcents(subtotal)} />
      <Row label="GST 10%" value={fmtAUDcents(gst)} />
      <div style={{ height: 1, width: 260, background: 'var(--border)', margin: '4px 0' }} />
      <Row label="Total inc-GST (AUD)" value={fmtAUDcents(total)} big />
    </div>
  );
}
function Row({ label, value, big }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', width: 260 }}>
      <span style={{ color: 'var(--ink-70)' }}>{label}</span>
      <span style={{ color: 'var(--ink)', fontWeight: big ? 600 : 400, fontSize: big ? 15 : 13 }}>{value}</span>
    </div>
  );
}

Object.assign(window, { AIQuote });
