/* ============ AI tools (Claude-powered) ============ */
async function askClaudeJSON(prompt) {
  let text = await window.claude.complete(prompt);
  text = (text || '').trim().replace(/^```(json)?/i, '').replace(/```$/, '').trim();
  return JSON.parse(text);
}
function aiAvailable() { return !!(window.claude && window.claude.complete); }

/* ---- 1. AI Rehab Estimator (+ voice notes) ---- */
function AIRehabButton({ deal, update }) {
  const [open, setOpen] = React.useState(false);
  return (
    <React.Fragment>
      <button className="ai-mini-btn" title="AI rehab estimate" onClick={() => setOpen(true)}>
        <span className="ai-spark">✦</span> AI
      </button>
      {open ? <AIRehabModal deal={deal} update={update} onClose={() => setOpen(false)} /> : null}
    </React.Fragment>
  );
}

function AIRehabModal({ deal, update, onClose }) {
  const [desc, setDesc] = React.useState('');
  const [state, setState] = React.useState('idle');
  const [items, setItems] = React.useState([]);
  const [err, setErr] = React.useState('');
  const [recording, setRecording] = React.useState(false);
  const rec = React.useRef(null);

  const startVoice = () => {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SR) { setErr('Voice input is not supported in this browser. Type your notes instead.'); return; }
    const r = new SR(); r.continuous = true; r.interimResults = true; r.lang = 'en-US';
    const base = desc ? desc + ' ' : '';
    r.onresult = (e) => { let t = ''; for (let i = 0; i < e.results.length; i++) t += e.results[i][0].transcript; setDesc(base + t); };
    r.onerror = () => setRecording(false);
    r.onend = () => setRecording(false);
    r.start(); rec.current = r; setRecording(true);
  };
  const stopVoice = () => { if (rec.current) rec.current.stop(); setRecording(false); };

  const estimate = async () => {
    if (!aiAvailable()) { setErr('AI is unavailable in this view.'); return; }
    if (!desc.trim()) { setErr('Describe the property condition first.'); return; }
    setState('loading'); setErr('');
    const p = deal.property;
    const prompt = `You are a fix-and-flip general contractor. Based on this walkthrough of a ${p.sqft} sqft, ${p.beds}bd/${p.baths}ba home, produce a rehab budget broken into line items with realistic US dollar costs.\n\nWalkthrough notes:\n${desc}\n\nRespond ONLY with minified JSON, no markdown:\n{"items":[{"category":"<short label>","cost":<integer dollars>}],"total":<integer>,"note":"<one short sentence>"}`;
    try { const j = await askClaudeJSON(prompt); setItems(j.items || []); setState('done'); }
    catch (e) { setErr(e.message || 'Could not get estimate. Try again.'); setState('idle'); }
  };

  const total = items.reduce((a, b) => a + (Number(b.cost) || 0), 0);
  const apply = () => {
    update({ rehab: items.map((it) => ({ k: it.category, v: Math.round(it.cost) || 0, custom: true })) });
    onClose();
  };

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 720 }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h2><span className="ai-spark">✦</span> AI Rehab Estimator</h2>
          <button className="btn" onClick={onClose}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12" /></svg></button>
        </div>
        <div className="modal-body" style={{ gridTemplateColumns: '1fr', display: 'block' }}>
          <div style={{ fontSize: 13, color: 'var(--muted)', lineHeight: 1.5, marginBottom: 10 }}>
            Describe the condition room by room — or use voice to dictate your walkthrough. Claude turns it into a line-item rehab budget.
          </div>
          <div style={{ position: 'relative' }}>
            <textarea className="ai-textarea" value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="e.g. Kitchen needs new cabinets and counters, roof is 20 years old, all flooring is worn carpet, two bathrooms need full gut, exterior needs paint…"></textarea>
            <button className={'voice-btn' + (recording ? ' rec' : '')} onClick={recording ? stopVoice : startVoice} title="Dictate">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" /><path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v4" /></svg>
              {recording ? 'Stop' : 'Voice'}
            </button>
          </div>
          {err ? <div className="ai-err">{err}</div> : null}
          {state === 'loading' ? <div className="ai-loading"><span className="spin" style={{ borderTopColor: 'var(--green-600)', borderColor: 'rgba(63,122,95,.3)' }}></span> Estimating rehab costs…</div> : null}
          {state === 'done' && items.length ? (
            <div className="ai-rehab-result">
              <table className="cmp-tbl"><thead><tr><th>Category</th><th>Estimated cost</th></tr></thead>
                <tbody>{items.map((it, i) => <tr key={i}><td>{it.category}</td><td>{fmtMoney(it.cost)}</td></tr>)}
                  <tr className="cmp-em"><td>Total</td><td>{fmtMoney(total)}</td></tr>
                </tbody>
              </table>
            </div>
          ) : null}
        </div>
        <div className="modal-foot">
          <div style={{ fontSize: 11.5, color: 'var(--muted)', flex: 1, lineHeight: 1.4 }}>AI estimate — verify with contractor bids. Applying replaces the Rehab table.</div>
          {state === 'done' && items.length ? <button className="btn primary" onClick={apply}>Apply to rehab table → {fmtMoney(total)}</button>
            : <button className="btn primary" onClick={estimate} disabled={state === 'loading'}>{state === 'loading' ? 'Working…' : 'Estimate rehab'}</button>}
        </div>
      </div>
    </div>
  );
}

/* ---- 2. AI ARV Suggester ---- */
function AIARVSuggester({ deal, update }) {
  const [state, setState] = React.useState('idle');
  const [res, setRes] = React.useState(null);
  const [err, setErr] = React.useState('');

  const run = async () => {
    if (!aiAvailable()) { setErr('AI unavailable here.'); setState('error'); return; }
    setState('loading'); setErr('');
    const p = deal.property;
    const live = (deal.comps && deal.comps.list || []).map((c) => `${c.address}: $${c.price} / ${c.sqft}sqft ($${c.ppsf}/sqft), ${c.beds}bd, ${c.dom}DOM`).join('\n');
    const manual = (deal.manualComps || []).filter((c) => c.price).map((c) => `${c.address}: $${c.price} / ${c.sqft}sqft, ${c.condition}`).join('\n');
    const prompt = `You are a real-estate appraiser. Estimate the After Repair Value (renovated) for the subject home: ${p.address}, ${p.city}, ${p.state} — ${p.sqft} sqft, ${p.beds}bd/${p.baths}ba.\n\nComparable sales:\n${live || 'none'}\n${manual || ''}\n\nWeight by similarity in size, condition and proximity. Respond ONLY with minified JSON:\n{"arv":<integer>,"low":<integer>,"high":<integer>,"ppsf":<integer>,"reasoning":"<two sentences>"}`;
    try { const j = await askClaudeJSON(prompt); setRes(j); setState('done'); }
    catch (e) { setErr(e.message || 'Could not get AI response.'); setState('error'); }
  };

  return (
    <div className="ai-card" style={{ marginBottom: 16 }}>
      <div className="ai-head">
        <div className="ai-title"><span className="ai-spark">✦</span> AI ARV Suggester <span className="ai-badge">Claude</span></div>
        <button className="btn primary" onClick={run} disabled={state === 'loading'}>
          {state === 'loading' ? <span className="spin"></span> : <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2l2.4 7.4H22l-6 4.4 2.3 7.2L12 16.8 5.7 21l2.3-7.2-6-4.4h7.6z" /></svg>}
          {state === 'done' ? 'Re-analyze' : 'Suggest ARV from comps'}
        </button>
      </div>
      {err ? <div className="ai-err">{err}</div> : null}
      {state === 'done' && res ? (
        <div className="ai-result" style={{ marginTop: 12 }}>
          <div className="ai-score-wrap">
            <div>
              <div className="ai-verdict" style={{ color: 'var(--green-700)' }}>{fmtMoney(res.arv)}</div>
              <div className="ai-summary">Range {fmtMoney(res.low)} – {fmtMoney(res.high)} · ~{fmtMoney(res.ppsf)}/sqft</div>
            </div>
            <button className="btn primary" style={{ marginLeft: 'auto' }} onClick={() => update({ terms: { ...deal.terms, sellingPrice: Math.round(res.arv) } })}>Use as ARV →</button>
          </div>
          <div className="ai-summary" style={{ marginTop: 10 }}>{res.reasoning}</div>
          <div className="ai-disclaimer">AI estimate — verify with a licensed appraisal/BPO.</div>
        </div>
      ) : <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 8 }}>Analyzes your live + manual comps and suggests a defensible ARV with reasoning.</div>}
    </div>
  );
}

/* ---- 3. AI Market Analysis ---- */
function AIMarketAnalysis({ deal }) {
  const [state, setState] = React.useState('idle');
  const [text, setText] = React.useState('');
  const [err, setErr] = React.useState('');
  const run = async () => {
    if (!aiAvailable()) { setErr('AI unavailable here.'); setState('error'); return; }
    setState('loading'); setErr('');
    const p = deal.property;
    const prompt = `You are a local real-estate market analyst. Give a concise neighborhood & market summary for ${p.address ? p.address + ', ' : ''}${p.city}, ${p.state} ${p.zip} relevant to a fix-and-flip investor. Cover demand, typical buyer, price trend direction, days-on-market feel, and any flip considerations. 4-6 short bullet points, each starting with "• ". Plain text only, no markdown headers.`;
    try { const t = await window.claude.complete(prompt); setText(t || ''); setState('done'); }
    catch (e) { setErr(e.message || 'Could not reach AI.'); setState('error'); }
  };
  return (
    <div className="card" style={{ marginTop: 16 }}>
      <div className="card-head"><h3>AI Market Analysis</h3>
        <button className="btn" onClick={run} disabled={state === 'loading'}>{state === 'loading' ? <span className="spin"></span> : <span className="ai-spark">✦</span>} {state === 'done' ? 'Refresh' : 'Analyze market'}</button>
      </div>
      <div className="card-body">
        {err ? <div className="ai-err">{err}</div> : null}
        {state === 'idle' ? <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>Get a Claude-generated neighborhood &amp; market read for this address.</div> : null}
        {state === 'loading' ? <div className="ai-loading"><span className="spin" style={{ borderTopColor: 'var(--green-600)', borderColor: 'rgba(63,122,95,.3)' }}></span> Analyzing the market…</div> : null}
        {state === 'done' ? <div className="ai-market-text">{text.split('\n').filter(Boolean).map((l, i) => <p key={i}>{l}</p>)}<div className="ai-disclaimer">AI-generated from general knowledge — verify local specifics.</div></div> : null}
      </div>
    </div>
  );
}

/* ---- 4. In-app chat assistant ---- */
function AIChat({ deal, calc }) {
  const [open, setOpen] = React.useState(false);
  const [msgs, setMsgs] = React.useState([{ role: 'assistant', content: "Hi! Ask me anything about this deal — offer price, risks, financing, what-ifs." }]);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const bodyRef = React.useRef(null);

  React.useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [msgs, open]);

  const send = async () => {
    if (!input.trim() || busy) return;
    if (!aiAvailable()) { setMsgs((m) => [...m, { role: 'assistant', content: 'AI is unavailable in this view.' }]); return; }
    const q = input.trim();
    const next = [...msgs, { role: 'user', content: q }];
    setMsgs(next); setInput(''); setBusy(true);
    const ctx = dealSummaryForAI(deal, calc);
    const messages = [
      { role: 'user', content: `You are a sharp, concise fix-and-flip advisor embedded in a deal analyzer. Here is the current deal:\n${ctx}\n\nAnswer the user's questions about THIS deal specifically, using the numbers above. Be brief and practical.\n\nQuestion: ${q}` },
      ...next.slice(1).filter((m) => m.role === 'user').slice(0, -1).map((m) => ({ role: 'user', content: m.content })),
    ];
    try {
      const t = await window.claude.complete({ messages: [{ role: 'user', content: messages[0].content }] });
      setMsgs((m) => [...m, { role: 'assistant', content: t || '…' }]);
    } catch (e) { setMsgs((m) => [...m, { role: 'assistant', content: 'Sorry — I had trouble answering. Try again.' }]); }
    setBusy(false);
  };

  return (
    <React.Fragment>
      <button className="chat-fab" onClick={() => setOpen(!open)} title="Ask AI about this deal">
        {open ? <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
          : <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" /></svg>}
      </button>
      {open ? (
        <div className="chat-panel">
          <div className="chat-head"><span className="ai-spark">✦</span> Deal Assistant <span className="ai-badge">Claude</span></div>
          <div className="chat-body" ref={bodyRef}>
            {msgs.map((m, i) => <div key={i} className={'chat-msg ' + m.role}>{m.content}</div>)}
            {busy ? <div className="chat-msg assistant"><span className="spin" style={{ borderTopColor: 'var(--green-600)', borderColor: 'rgba(63,122,95,.3)', display: 'inline-block', verticalAlign: 'middle' }}></span></div> : null}
          </div>
          <div className="chat-input">
            <input value={input} placeholder="Ask about this deal…" onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()} />
            <button className="btn primary" onClick={send} disabled={busy}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4z" /></svg></button>
          </div>
        </div>
      ) : null}
    </React.Fragment>
  );
}

/* ---- 5. AI Rehab Planner (dedicated tab with checkboxes) ---- */
const REHAB_CATALOG = [
  { id: 'kitchen_full',      label: 'Kitchen – Full Remodel',              group: 'Kitchen' },
  { id: 'kitchen_partial',   label: 'Kitchen – Cabinet/Counter Update',     group: 'Kitchen' },
  { id: 'bath_full',         label: 'Bathrooms – Full Gut (per bath)',       group: 'Bathrooms' },
  { id: 'bath_cosmetic',     label: 'Bathrooms – Cosmetic Update (per bath)',group: 'Bathrooms' },
  { id: 'flooring_lvp',      label: 'Flooring – LVP / Laminate',           group: 'Flooring' },
  { id: 'flooring_hardwood', label: 'Flooring – Hardwood',                 group: 'Flooring' },
  { id: 'flooring_carpet',   label: 'Flooring – Carpet',                   group: 'Flooring' },
  { id: 'flooring_tile',     label: 'Flooring – Tile (kitchen/bath)',       group: 'Flooring' },
  { id: 'roof_replace',      label: 'Roof – Full Replacement',              group: 'Roof' },
  { id: 'roof_repair',       label: 'Roof – Partial Repair',               group: 'Roof' },
  { id: 'hvac_full',         label: 'HVAC – Full System Replacement',       group: 'HVAC' },
  { id: 'hvac_service',      label: 'HVAC – Service / Tune-up',             group: 'HVAC' },
  { id: 'electrical_panel',  label: 'Electrical – Panel Upgrade',           group: 'Electrical' },
  { id: 'electrical_rewire', label: 'Electrical – Full Rewire',             group: 'Electrical' },
  { id: 'electrical_misc',   label: 'Electrical – Outlets / Lighting',      group: 'Electrical' },
  { id: 'plumbing_repipe',   label: 'Plumbing – Full Repipe',               group: 'Plumbing' },
  { id: 'plumbing_fixtures', label: 'Plumbing – Fixtures & Updates',        group: 'Plumbing' },
  { id: 'windows_all',       label: 'Windows – Full Replacement',           group: 'Windows' },
  { id: 'windows_partial',   label: 'Windows – Partial (selected only)',    group: 'Windows' },
  { id: 'ext_paint',         label: 'Exterior – Paint',                     group: 'Exterior' },
  { id: 'ext_siding',        label: 'Exterior – Siding Replacement',        group: 'Exterior' },
  { id: 'ext_landscape',     label: 'Exterior – Landscaping / Curb Appeal', group: 'Exterior' },
  { id: 'ext_driveway',      label: 'Exterior – Driveway / Concrete',       group: 'Exterior' },
  { id: 'int_paint',         label: 'Interior – Full Paint',                group: 'Interior' },
  { id: 'int_drywall',       label: 'Interior – Drywall Repair',            group: 'Interior' },
  { id: 'int_doors',         label: 'Interior – Doors & Trim',              group: 'Interior' },
  { id: 'garage_door',       label: 'Garage – Door Replacement',            group: 'Garage' },
  { id: 'foundation',        label: 'Foundation – Repair / Stabilization',  group: 'Foundation' },
  { id: 'deck_patio',        label: 'Deck / Patio – Build or Repair',       group: 'Outdoor' },
  { id: 'pool',              label: 'Pool – Remodel / Repair',              group: 'Outdoor' },
];

function AIRehabPlanner({ deal, update }) {
  const p = deal.property;
  const t = deal.terms;
  const sqft = t.livingArea || p.sqft || 0;
  const beds = t.beds || p.beds || 0;
  const baths = t.baths || p.baths || 0;
  const location = [p.city, p.county, p.state].filter(Boolean).join(', ') || [p.city, p.state].filter(Boolean).join(', ');

  const groups = [...new Set(REHAB_CATALOG.map((i) => i.group))];
  const [selected, setSelected] = React.useState({});
  const [notes, setNotes] = React.useState('');
  const [state, setState] = React.useState('idle');
  const [result, setResult] = React.useState(null);
  const [err, setErr] = React.useState('');

  const toggle = (id) => setSelected((s) => ({ ...s, [id]: !s[id] }));
  const selectAll = (group) => {
    const ids = REHAB_CATALOG.filter((i) => i.group === group).map((i) => i.id);
    const allOn = ids.every((id) => selected[id]);
    setSelected((s) => { const n = { ...s }; ids.forEach((id) => { n[id] = !allOn; }); return n; });
  };
  const selectedItems = REHAB_CATALOG.filter((i) => selected[i.id]);
  const total = (result?.items || []).reduce((s, i) => s + (Number(i.cost) || 0), 0);

  const estimate = async () => {
    if (!aiAvailable()) { setErr('AI unavailable — configure your Claude API key in Settings.'); return; }
    if (selectedItems.length === 0) { setErr('Select at least one renovation item.'); return; }
    setState('loading'); setErr('');
    const loc = location || 'the property location';
    const prompt = `You are an expert fix-and-flip general contractor with deep knowledge of local labor and material costs across the US.

Estimate realistic rehab costs for the following property and selected renovation items. Use current (2024-2025) pricing for ${loc}.

Property details:
- Location: ${loc}
- Size: ${sqft ? sqft.toLocaleString() + ' sqft' : 'unknown sqft'}
- Bedrooms: ${beds || 'unknown'} | Bathrooms: ${baths || 'unknown'}
${notes ? '- Notes: ' + notes : ''}

Selected renovations:
${selectedItems.map((i) => `- ${i.label}`).join('\n')}

Instructions:
- Use local market pricing for ${p.city || 'this area'}, ${p.state || ''}
- For sqft-based items (flooring, paint, etc.) base cost on ${sqft || 'estimated'} sqft
- For per-unit items (bathrooms, windows) use realistic unit counts from the bed/bath data
- Provide realistic mid-range contractor pricing (not DIY, not premium luxury)

Respond ONLY with minified JSON, no markdown:
{"items":[{"category":"<label matching selected item>","cost":<integer>,"note":"<brief: e.g. '${sqft} sqft @ $4.50/sqft' or '3 units @ $8,000 each'>"}],"total":<integer>,"summary":"<2 sentences about cost factors for ${loc}>"}`;

    try {
      const j = await askClaudeJSON(prompt);
      setResult(j);
      setState('done');
    } catch (e) {
      setErr(e.message || 'Could not get AI estimate. Try again.');
      setState('idle');
    }
  };

  const applyToRehab = () => {
    if (!result?.items?.length) return;
    update({ rehab: result.items.map((it) => ({ k: it.category, v: Math.round(it.cost) || 0, custom: true })) });
  };

  return (
    <div>
      <div className="offer-guidance-box">
        <div className="offer-guidance-title">AI Rehab Cost Planner</div>
        <div className="offer-guidance-copy">
          Select what needs renovation, then Claude researches average contractor costs for {location || 'your area'} — adjusted for sqft and local market rates.
        </div>
      </div>

      <div className="grid">
        <div className="col">
          <div className="card">
            <div className="card-head"><h3>Select Renovation Items</h3></div>
            <div className="card-body">
              {groups.map((group) => {
                const groupItems = REHAB_CATALOG.filter((i) => i.group === group);
                const allOn = groupItems.every((i) => selected[i.id]);
                return (
                  <div key={group} style={{ marginBottom: 14 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
                      <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.07em', color: 'var(--muted)' }}>{group}</div>
                      <button
                        onClick={() => selectAll(group)}
                        style={{ fontSize: 10, padding: '1px 7px', background: allOn ? 'var(--sage-soft)' : '#f0f0f0', border: '1px solid var(--line)', borderRadius: 3, cursor: 'pointer', color: 'var(--ink)' }}
                      >
                        {allOn ? 'Deselect all' : 'Select all'}
                      </button>
                    </div>
                    {groupItems.map((item) => (
                      <label key={item.id} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer', padding: '3px 0' }}>
                        <input type="checkbox" checked={!!selected[item.id]} onChange={() => toggle(item.id)} />
                        {item.label}
                      </label>
                    ))}
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <div className="col">
          <div className="card">
            <div className="card-head"><h3>Property & Location</h3></div>
            <div className="card-body">
              <div className="frow"><div className="frow-label">Location</div><div className="in zero">{location || '—  (fill in property address)'}</div></div>
              <div className="frow"><div className="frow-label">Size</div><div className="in zero">{sqft ? sqft.toLocaleString() + ' sqft' : '—'}</div></div>
              <div className="frow"><div className="frow-label">Bed / Bath</div><div className="in zero">{beds ? beds + 'bd' : '—'} / {baths ? baths + 'ba' : '—'}</div></div>
              <div style={{ marginTop: 12 }}>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 5 }}>Additional notes (optional)</div>
                <textarea
                  className="ai-textarea"
                  style={{ height: 72 }}
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  placeholder="e.g. 3 full bathrooms need gut; roof is 15 yrs old; master suite addition planned…"
                />
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <h3>{selectedItems.length} item{selectedItems.length !== 1 ? 's' : ''} selected</h3>
              <button
                className="btn primary"
                onClick={estimate}
                disabled={state === 'loading' || selectedItems.length === 0}
              >
                {state === 'loading' ? <span className="spin"></span> : <span className="ai-spark">✦</span>}
                {state === 'loading' ? 'Researching costs…' : 'Get AI Estimate'}
              </button>
            </div>
            <div className="card-body">
              {err ? <div className="ai-err">{err}</div> : null}
              {selectedItems.length === 0 ? (
                <div style={{ fontSize: 13, color: 'var(--muted)' }}>Select renovation items on the left, then click Get AI Estimate.</div>
              ) : (
                <ul style={{ margin: 0, padding: '0 0 0 16px', fontSize: 13, lineHeight: 1.7 }}>
                  {selectedItems.map((i) => <li key={i.id}>{i.label}</li>)}
                </ul>
              )}
            </div>
          </div>

          {state === 'done' && result?.items?.length ? (
            <div className="card">
              <div className="card-head">
                <h3>AI Cost Estimate</h3>
                <button className="btn primary" onClick={applyToRehab}>Apply to Rehab Table →</button>
              </div>
              <div className="card-body">
                <table className="cmp-tbl" style={{ width: '100%' }}>
                  <thead>
                    <tr>
                      <th>Item</th>
                      <th style={{ textAlign: 'right', width: 100 }}>Cost</th>
                      <th style={{ width: 160 }}>Basis</th>
                    </tr>
                  </thead>
                  <tbody>
                    {result.items.map((it, i) => (
                      <tr key={i}>
                        <td>{it.category}</td>
                        <td style={{ textAlign: 'right' }}>{fmtMoney(it.cost)}</td>
                        <td style={{ fontSize: 11, color: 'var(--muted)' }}>{it.note || ''}</td>
                      </tr>
                    ))}
                    <tr className="cmp-em">
                      <td>Total</td>
                      <td style={{ textAlign: 'right' }}>{fmtMoney(total)}</td>
                      <td></td>
                    </tr>
                  </tbody>
                </table>
                {result.summary ? <div style={{ marginTop: 10, fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.5 }}>{result.summary}</div> : null}
                <div className="ai-disclaimer">AI estimate — always verify with licensed contractor bids before committing.</div>
              </div>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AIRehabButton, AIARVSuggester, AIMarketAnalysis, AIChat, AIRehabPlanner });
