// CmaPage.jsx — Comparative Market Analysis white-label (Vague 4 PR 4.4)
// Suffixe alias : CM (CmaPage)
//
// Route : #/courtier/cma
// Acces reserve au plan Pro (gating cote backend via require_pro_plan).
//
// Convention projet : pas d'import/export, React global, fenetres window.*.

function CmaPage({ user, lang }) {
  const {
    useState: useSCM,
    useMemo: useMCM,
    useCallback: useCBCM,
  } = React;
  const FR = lang !== 'en';

  const api = (window.vestora && window.vestora.brokerApi) || null;
  const TT = window.TermTooltip || (({ children }) => <span>{children}</span>);

  // ── Form state ───────────────────────────────────────────────────────────
  const [form, setForm] = useSCM({
    subjectAddress: '',
    subjectCity: '',
    subjectType: 'plex',
    subjectUnits: '',
    subjectYearBuilt: '',
    subjectAreaSqm: '',
    subjectPriceTarget: '',
  });

  // ── Resultats ────────────────────────────────────────────────────────────
  const [result, setResult] = useSCM(null);
  const [loading, setLoading] = useSCM(false);
  const [error, setError] = useSCM(null);
  const [pdfLoading, setPdfLoading] = useSCM(false);
  const [pdfError, setPdfError] = useSCM(null);

  // ── Helpers format ───────────────────────────────────────────────────────
  const fmtMoney = (v) => {
    if (v == null || Number.isNaN(Number(v))) return '—';
    return new Intl.NumberFormat(FR ? 'fr-CA' : 'en-CA', {
      style: 'currency', currency: 'CAD', maximumFractionDigits: 0,
    }).format(Number(v));
  };
  const fmtArea = (v) => {
    if (v == null) return '—';
    return `${Number(v).toFixed(0)} m²`;
  };
  const fmtPct = (v) => (v == null ? '—' : `${Number(v).toFixed(1)}%`);

  // ── Handlers ─────────────────────────────────────────────────────────────
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = useCBCM(async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (!api) {
      setError(FR ? 'API courtier indisponible.' : 'Broker API unavailable.');
      return;
    }
    if (!form.subjectAddress || form.subjectAddress.length < 3) {
      setError(FR ? 'Adresse requise.' : 'Address required.');
      return;
    }
    setLoading(true);
    setError(null);
    const res = await api.computeCma(form);
    setLoading(false);
    if (!res.ok) {
      setError((res.error && res.error.message) || (FR ? 'Erreur CMA.' : 'CMA error.'));
      return;
    }
    setResult(res.data);
  }, [api, form, FR]);

  const downloadPdf = useCBCM(async () => {
    if (!api) return;
    setPdfLoading(true);
    setPdfError(null);
    const res = await api.generateCmaPdf(form);
    setPdfLoading(false);
    if (!res.ok) {
      setPdfError((res.error && res.error.message) || (FR ? 'Erreur PDF.' : 'PDF error.'));
      return;
    }
    const url = res.data && res.data.pdf_url;
    if (url) {
      window.open(url, '_blank', 'noopener');
    }
  }, [api, form]);

  // ── Confiance badge color ────────────────────────────────────────────────
  const confidenceMeta = useMCM(() => {
    if (!result || !result.suggestion) return null;
    const c = result.suggestion.confidence;
    return {
      color: c === 'high' ? '#10b981' : c === 'medium' ? '#f59e0b' : '#ef4444',
      bg: c === 'high' ? '#d1fae5' : c === 'medium' ? '#fef3c7' : '#fee2e2',
      label: c === 'high' ? (FR ? 'Confiance elevee' : 'High confidence')
        : c === 'medium' ? (FR ? 'Confiance moyenne' : 'Medium confidence')
        : (FR ? 'Confiance faible' : 'Low confidence'),
    };
  }, [result, FR]);

  // ── Render ───────────────────────────────────────────────────────────────
  return (
    <div style={{ background: 'var(--bg, #faf7f2)', minHeight: '100vh', padding: '20px 16px 60px' }}>
      <div style={{ maxWidth: 1080, margin: '0 auto' }}>

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
          <button
            onClick={() => window.navigateTo('#/courtier')}
            style={{
              padding: '6px 12px', borderRadius: 6,
              border: '1px solid var(--border, #e5e7eb)',
              background: '#fff', cursor: 'pointer', fontSize: 13,
            }}
          >
            ← {FR ? 'Retour dashboard' : 'Back to dashboard'}
          </button>
          <h1 style={{ margin: 0, fontSize: 22, color: 'var(--ink, #0F172A)' }}>
            <TT term="cma" lang={lang}>{FR ? 'Analyse comparative (CMA)' : 'Comparative Market Analysis (CMA)'}</TT>
          </h1>
        </div>

        <p style={{ color: 'var(--ink-2, #64748b)', maxWidth: 720, fontSize: 13, lineHeight: 1.55, marginBottom: 18 }}>
          {FR
            ? <>Generez un CMA pour un mandat vendeur : top 8 <TT term="comparables" lang={lang}>comparables</TT> actifs, fourchette de prix suggeree et PDF brande. v1 limitee aux annonces actives Centris — les ventes historiques arrivent en Vague 6.</>
            : <>Generate a CMA for a seller listing: top 8 active comparables, suggested price range and white-label PDF. v1 limited to active Centris listings — historical sales coming in Wave 6.</>}
        </p>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(280px, 360px) 1fr', gap: 20, alignItems: 'start' }}>

          {/* ── Form ──────────────────────────────────────────────────────── */}
          <form onSubmit={submit} style={{
            background: '#fff', borderRadius: 10, padding: 18,
            boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
            position: 'sticky', top: 18,
          }}>
            <h3 style={{ margin: '0 0 14px 0', fontSize: 15, color: 'var(--ink, #0F172A)' }}>
              {FR ? 'Proprete a evaluer' : 'Property to assess'}
            </h3>

            <Field label={FR ? 'Adresse complete *' : 'Full address *'}>
              <input
                type="text"
                required
                value={form.subjectAddress}
                onChange={(e) => update('subjectAddress', e.target.value)}
                placeholder={FR ? '123 rue Principale, Montreal, QC' : '123 Main St, Montreal, QC'}
                style={inputStyle}
              />
            </Field>

            <Field label={FR ? 'Ville (si pas dans l\'adresse)' : 'City (if not in address)'}>
              <input
                type="text"
                value={form.subjectCity}
                onChange={(e) => update('subjectCity', e.target.value)}
                placeholder={FR ? 'Montreal' : 'Montreal'}
                style={inputStyle}
              />
            </Field>

            <Field label={FR ? 'Type *' : 'Type *'}>
              <select
                value={form.subjectType}
                onChange={(e) => update('subjectType', e.target.value)}
                style={inputStyle}
              >
                <option value="plex">{FR ? 'Plex (2-4 logements)' : 'Plex (2-4 units)'}</option>
                <option value="multilog">{FR ? 'Multilogement (5+)' : 'Multifamily (5+)'}</option>
                <option value="condo">{FR ? 'Condo' : 'Condo'}</option>
                <option value="unifamilial">{FR ? 'Unifamilial' : 'Single family'}</option>
                <option value="mixte">{FR ? 'Mixte (res+commercial)' : 'Mixed (res+commercial)'}</option>
              </select>
            </Field>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <Field label={FR ? 'Logements' : 'Units'}>
                <input
                  type="number" min="0"
                  value={form.subjectUnits}
                  onChange={(e) => update('subjectUnits', e.target.value)}
                  style={inputStyle}
                />
              </Field>
              <Field label={FR ? 'Annee constr.' : 'Year built'}>
                <input
                  type="number" min="1700" max="2100"
                  value={form.subjectYearBuilt}
                  onChange={(e) => update('subjectYearBuilt', e.target.value)}
                  style={inputStyle}
                />
              </Field>
            </div>

            <Field label={FR ? 'Surface (m²)' : 'Area (m²)'}>
              <input
                type="number" min="0" step="0.1"
                value={form.subjectAreaSqm}
                onChange={(e) => update('subjectAreaSqm', e.target.value)}
                style={inputStyle}
              />
            </Field>

            <Field label={FR ? 'Prix cible (optionnel)' : 'Target price (optional)'}>
              <input
                type="number" min="0"
                value={form.subjectPriceTarget}
                onChange={(e) => update('subjectPriceTarget', e.target.value)}
                placeholder={FR ? 'Pour calculer le delta' : 'For delta calc'}
                style={inputStyle}
              />
            </Field>

            <button
              type="submit"
              disabled={loading}
              style={{
                width: '100%', marginTop: 8, padding: '10px 14px',
                background: 'var(--accent, #0F172A)', color: '#fff',
                border: 'none', borderRadius: 6, fontWeight: 600, fontSize: 14,
                cursor: loading ? 'wait' : 'pointer', opacity: loading ? 0.7 : 1,
              }}
            >
              {loading
                ? (FR ? 'Calcul en cours…' : 'Computing…')
                : (FR ? 'Calculer le CMA' : 'Compute CMA')}
            </button>

            {error && (
              <div style={{
                marginTop: 10, padding: '8px 10px',
                background: '#fee2e2', color: '#991b1b',
                borderRadius: 6, fontSize: 12,
              }}>{error}</div>
            )}
          </form>

          {/* ── Resultats ─────────────────────────────────────────────────── */}
          <div>
            {!result ? (
              <div style={{
                background: '#fff', borderRadius: 10, padding: 36,
                textAlign: 'center', color: 'var(--ink-2, #64748b)',
                boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
              }}>
                <div style={{ fontSize: 36, marginBottom: 12 }}>🏘️</div>
                <p>{FR
                  ? 'Renseignez la proprete a gauche puis cliquez sur Calculer.'
                  : 'Fill in the property on the left and click Compute.'}</p>
              </div>
            ) : (
              <>
                {/* Subject summary */}
                <div style={{
                  background: '#fff', borderRadius: 10, padding: 16, marginBottom: 14,
                  boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
                }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-2, #64748b)', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                    {FR ? 'Proprete analysee' : 'Property analyzed'}
                  </div>
                  <div style={{ fontSize: 16, fontWeight: 600, marginTop: 4 }}>
                    {result.subject && result.subject.address}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-2, #64748b)', marginTop: 4 }}>
                    {result.subject && result.subject.type}
                    {result.subject && result.subject.units ? ` · ${result.subject.units} ${FR ? 'logements' : 'units'}` : ''}
                    {result.subject && result.subject.year_built ? ` · ${result.subject.year_built}` : ''}
                    {result.subject && result.subject.area_sqm ? ` · ${fmtArea(result.subject.area_sqm)}` : ''}
                  </div>
                </div>

                {/* Suggestion card */}
                <div style={{
                  background: '#fff', borderRadius: 10, padding: 18, marginBottom: 14,
                  borderLeft: `6px solid ${confidenceMeta ? confidenceMeta.color : '#64748b'}`,
                  boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
                }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-2, #64748b)', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                    {FR ? 'Fourchette suggeree' : 'Suggested range'}
                  </div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--ink, #0F172A)', marginTop: 4 }}>
                    {result.suggestion.suggestion_low
                      ? <>{fmtMoney(result.suggestion.suggestion_low)} – {fmtMoney(result.suggestion.suggestion_high)}</>
                      : (FR ? 'Indisponible' : 'Unavailable')}
                  </div>
                  {confidenceMeta && (
                    <span style={{
                      display: 'inline-block', marginTop: 6,
                      padding: '3px 10px', borderRadius: 12,
                      background: confidenceMeta.bg, color: confidenceMeta.color,
                      fontSize: 11, fontWeight: 600,
                    }}>
                      {confidenceMeta.label} · {result.stats.n_comparables} {FR ? 'comp.' : 'comp.'}
                    </span>
                  )}
                  {result.suggestion.delta_vs_target_pct != null && (
                    <div style={{ marginTop: 8, fontSize: 12, color: 'var(--ink-2, #64748b)' }}>
                      {FR ? 'Ecart prix cible :' : 'Target delta:'} <strong>{fmtPct(result.suggestion.delta_vs_target_pct)}</strong>
                    </div>
                  )}
                  <p style={{ fontSize: 12, color: '#444', lineHeight: 1.5, marginTop: 10, marginBottom: 12 }}>
                    {result.suggestion.rationale}
                  </p>

                  <button
                    onClick={downloadPdf}
                    disabled={pdfLoading}
                    style={{
                      padding: '8px 16px', background: '#0F172A', color: '#fff',
                      border: 'none', borderRadius: 6, fontSize: 13, fontWeight: 600,
                      cursor: pdfLoading ? 'wait' : 'pointer', opacity: pdfLoading ? 0.7 : 1,
                    }}
                  >
                    {pdfLoading
                      ? (FR ? 'Generation…' : 'Generating…')
                      : (FR ? '📄 Exporter PDF brande' : '📄 Export branded PDF')}
                  </button>
                  {pdfError && (
                    <div style={{ marginTop: 8, fontSize: 12, color: '#991b1b' }}>{pdfError}</div>
                  )}
                </div>

                {/* Stats card */}
                {(result.stats && (result.stats.price_per_sqm_median || result.stats.price_median)) && (
                  <div style={{
                    background: '#fff', borderRadius: 10, padding: 16, marginBottom: 14,
                    boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
                  }}>
                    <div style={{ fontSize: 11, color: 'var(--ink-2, #64748b)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>
                      {result.stats.price_per_sqm_median
                        ? (FR ? 'Statistiques prix/m²' : 'Price/m² statistics')
                        : (FR ? 'Statistiques prix' : 'Price statistics')}
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
                      {result.stats.price_per_sqm_median ? (
                        <>
                          <StatCard label="P25" value={`${fmtMoney(result.stats.price_per_sqm_p25)}/m²`} />
                          <StatCard label={FR ? 'Mediane' : 'Median'} value={`${fmtMoney(result.stats.price_per_sqm_median)}/m²`} />
                          <StatCard label="P75" value={`${fmtMoney(result.stats.price_per_sqm_p75)}/m²`} />
                        </>
                      ) : (
                        <>
                          <StatCard label="P25" value={fmtMoney(result.stats.price_p25)} />
                          <StatCard label={FR ? 'Mediane' : 'Median'} value={fmtMoney(result.stats.price_median)} />
                          <StatCard label="P75" value={fmtMoney(result.stats.price_p75)} />
                        </>
                      )}
                    </div>
                  </div>
                )}

                {/* Comparables table */}
                <div style={{
                  background: '#fff', borderRadius: 10, padding: 16, marginBottom: 14,
                  boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
                }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-2, #64748b)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>
                    {FR ? `Top ${result.comparables.length} comparables actifs` : `Top ${result.comparables.length} active comparables`}
                  </div>
                  {result.comparables.length === 0 ? (
                    <div style={{ padding: 24, textAlign: 'center', color: 'var(--ink-2, #64748b)', fontStyle: 'italic' }}>
                      {FR ? 'Aucun comparable trouve. Elargissez les criteres.' : 'No comparable found. Broaden criteria.'}
                    </div>
                  ) : (
                    <div style={{ overflowX: 'auto' }}>
                      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                        <thead>
                          <tr style={{ background: '#f8f8f6', color: 'var(--ink-2, #64748b)' }}>
                            <th style={thStyle}>{FR ? 'Adresse' : 'Address'}</th>
                            <th style={thStyle}>{FR ? 'Ville' : 'City'}</th>
                            <th style={thStyle}>{FR ? 'Prix' : 'Price'}</th>
                            <th style={thStyle}>m²</th>
                            <th style={thStyle}>$/m²</th>
                            <th style={thStyle}>U.</th>
                            <th style={thStyle}>{FR ? 'Annee' : 'Year'}</th>
                            <th style={thStyle}>{FR ? 'Score' : 'Score'}</th>
                          </tr>
                        </thead>
                        <tbody>
                          {result.comparables.map((c) => (
                            <tr key={c.listing_id} style={{ borderBottom: '1px solid #f0eee9' }}>
                              <td style={tdStyle}>
                                {c.listing_url
                                  ? <a href={c.listing_url} target="_blank" rel="noopener noreferrer" style={{ color: '#0F172A' }}>{c.address}</a>
                                  : c.address}
                              </td>
                              <td style={tdStyle}>{c.city || '—'}</td>
                              <td style={tdStyle}><strong>{fmtMoney(c.price)}</strong></td>
                              <td style={tdStyle}>{c.area_sqm ? c.area_sqm.toFixed(0) : '—'}</td>
                              <td style={tdStyle}>{c.price_per_sqm ? fmtMoney(c.price_per_sqm) : '—'}</td>
                              <td style={tdStyle}>{c.units || '—'}</td>
                              <td style={tdStyle}>{c.year_built || '—'}</td>
                              <td style={tdStyle}>{Math.round(c.similarity_score)}/100</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}
                </div>

                {/* Methodology */}
                <div style={{
                  background: '#faf7f2', borderRadius: 10, padding: 14,
                  fontSize: 11, color: '#444', lineHeight: 1.55,
                }}>
                  <strong>{FR ? 'Methodologie : ' : 'Methodology: '}</strong>{result.methodology}
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Helpers UI internes ──────────────────────────────────────────────────────

const inputStyle = {
  width: '100%', padding: '7px 9px', fontSize: 13,
  border: '1px solid var(--border, #e5e7eb)', borderRadius: 6,
  background: '#fff',
};

const thStyle = {
  padding: '8px 10px', textAlign: 'left', fontWeight: 600,
  borderBottom: '1px solid #e5e5e5',
};

const tdStyle = {
  padding: '8px 10px', verticalAlign: 'top',
};

function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <label style={{
        display: 'block', fontSize: 11, color: 'var(--ink-2, #64748b)',
        marginBottom: 3, fontWeight: 600,
      }}>{label}</label>
      {children}
    </div>
  );
}

function StatCard({ label, value }) {
  return (
    <div style={{
      background: '#f8f8f6', padding: '10px 12px', borderRadius: 6, textAlign: 'center',
    }}>
      <div style={{ fontSize: 10, color: '#666' }}>{label}</div>
      <div style={{ fontSize: 14, fontWeight: 600, color: '#0F172A', marginTop: 2 }}>{value}</div>
    </div>
  );
}

window.CmaPage = CmaPage;
