/* ============ Claude-powered AI features ============ */
function dealSummaryForAI(deal, calc) {
  const p = deal.property, t = deal.terms;
  return [
    `Property: ${p.address}, ${p.city}, ${p.state} ${p.zip} — ${p.beds}bd/${p.baths}ba, ${p.sqft} sqft, ${p.lotSize}ac lot.`,
    `Purchase (accepted) price: $${Math.round(t.acceptedPrice).toLocaleString()} ($${calc.acceptPerSqft.toFixed(0)}/sqft).`,
    `ARV / planned sale price: $${Math.round(t.sellingPrice).toLocaleString()} ($${calc.arvPerSqft.toFixed(0)}/sqft).`,
    `Rehab budget: $${Math.round(calc.rehabTotal).toLocaleString()}. Purchase costs: $${Math.round(calc.purchaseFeesSum).toLocaleString()}. Selling costs: $${Math.round(calc.sellingFeesSum).toLocaleString()}.`,
    `Holding: $${Math.round(calc.monthlyHolding).toLocaleString()}/mo for ${t.holdingMonths} months = $${Math.round(calc.holdingCost).toLocaleString()}.`,
    `All-in cost: $${Math.round(calc.allInCost).toLocaleString()}. Projected net profit: $${Math.round(calc.netProfit).toLocaleString()} (${calc.netMargin.toFixed(1)}% margin, ${calc.roi.toFixed(1)}% ROI).`,
    `Investor profit goal: ${t.profitGoalPct}% ($${Math.round(calc.profitGoal).toLocaleString()}). 70% rule max offer: $${Math.round(calc.mao).toLocaleString()}. Financing: ${t.purchaseType}.`,
  ].join('\n');
}

function AIDealScore({ deal, calc }) {
  const [state, setState] = React.useState('idle'); // idle | loading | done | error
  const [result, setResult] = React.useState(null);
  const [err, setErr] = React.useState('');

  const run = async () => {
    if (!window.claude || !window.claude.complete) { setErr('AI is unavailable in this view.'); setState('error'); return; }
    setState('loading'); setErr('');
    const prompt = `You are an expert real-estate fix-and-flip underwriter. Score this deal from 1 (terrible) to 10 (excellent) based on profit margin, ROI, the 70% rule, rehab-to-ARV ratio, and risk.\n\n${dealSummaryForAI(deal, calc)}\n\nRespond ONLY with minified JSON, no markdown, in this exact shape:\n{"score": <1-10 integer>, "verdict": "<3-5 word headline>", "summary": "<one sentence>", "strengths": ["<short>", "<short>"], "risks": ["<short>", "<short>"]}`;
    try {
      let text = await window.claude.complete(prompt);
      text = (text || '').trim().replace(/^```(json)?/i, '').replace(/```$/,'').trim();
      const j = JSON.parse(text);
      setResult(j); setState('done');
    } catch (e) {
      setErr(e.message || 'Could not get AI response. Try again.'); setState('error');
    }
  };

  const scoreColor = (s) => s >= 8 ? 'var(--green-700)' : s >= 5 ? 'var(--gold)' : 'var(--coral)';

  return (
    <div className="ai-card">
      <div className="ai-head">
        <div className="ai-title">
          <span className="ai-spark">✦</span> AI Deal Score
          <span className="ai-badge">Claude</span>
        </div>
        {state === 'done' || state === 'error' ? (
          <button className="btn" onClick={run}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M21 12a9 9 0 1 1-9-9" /><path d="M21 3v6h-6" /></svg>Re-score</button>
        ) : null}
      </div>

      {state === 'idle' ? (
        <div className="ai-idle">
          <p>Get an instant 1–10 underwriting score with strengths and risks for this deal.</p>
          <button className="btn primary" onClick={run}>
            <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>
            Score this deal
          </button>
        </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 numbers…</div>
      ) : null}

      {state === 'error' ? <div className="ai-err">{err}</div> : null}

      {state === 'done' && result ? (
        <div className="ai-result">
          <div className="ai-score-wrap">
            <div className="ai-score-ring" style={{ '--sc': scoreColor(result.score), background: `conic-gradient(${scoreColor(result.score)} ${result.score * 36}deg, var(--paper-2) 0)` }}>
              <div className="ai-score-inner"><span style={{ color: scoreColor(result.score) }}>{result.score}</span><small>/10</small></div>
            </div>
            <div>
              <div className="ai-verdict" style={{ color: scoreColor(result.score) }}>{result.verdict}</div>
              <div className="ai-summary">{result.summary}</div>
            </div>
          </div>
          <div className="ai-cols">
            <div>
              <div className="ai-col-h good">Strengths</div>
              <ul>{(result.strengths || []).map((s, i) => <li key={i}>{s}</li>)}</ul>
            </div>
            <div>
              <div className="ai-col-h bad">Risks</div>
              <ul>{(result.risks || []).map((s, i) => <li key={i}>{s}</li>)}</ul>
            </div>
          </div>
          <div className="ai-disclaimer">AI estimate for guidance only — verify independently. Not financial advice.</div>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { AIDealScore, dealSummaryForAI });
