/* ============ Advanced Comps & ARV with Filtering ============ */

function CompsTabAdvanced({ deal, calc, update }) {
  const t = deal.terms;
  const a = deal.analysis || {};
  const [status, setStatus] = React.useState('closed'); // active | closed | expired
  const [filters, setFilters] = React.useState({
    sqftRange: 15, // %
    exactBeds: true,
    exactBaths: true,
    subdivision: true,
  });
  const [comps, setComps] = React.useState(a.comps || []);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [manualComps, setManualComps] = React.useState(a.manualComps || []);

  const subjectSqft = t.livingArea || deal.property.sqft || 0;
  const subjectBeds = t.beds || deal.property.beds || 0;
  const subjectBaths = t.baths || deal.property.baths || 0;
  const subjectSubdivision = t.subdivision || '';
  const subjectCity = deal.property.city || '';

  // Filter comps based on criteria
  const filteredComps = comps.filter((c) => {
    // Status filter
    if (c.status !== status) return false;

    // Beds/Baths filter — skip when subject value is 0 (property not yet loaded)
    if (filters.exactBeds && subjectBeds > 0 && c.beds !== subjectBeds) return false;
    if (filters.exactBaths && subjectBaths > 0 && c.baths !== subjectBaths) return false;

    // Sqft range filter
    if (subjectSqft > 0 && filters.sqftRange) {
      const min = subjectSqft * (1 - filters.sqftRange / 100);
      const max = subjectSqft * (1 + filters.sqftRange / 100);
      if (c.sqft < min || c.sqft > max) return false;
    }

    // Subdivision filter
    if (filters.subdivision && subjectSubdivision) {
      if (!c.subdivision || !c.subdivision.toLowerCase().includes(subjectSubdivision.toLowerCase())) return false;
    }

    return true;
  });

  const avgPrice = filteredComps.length ? (filteredComps.reduce((s, c) => s + c.price, 0) / filteredComps.length) : 0;
  const avgSqft = filteredComps.length ? (filteredComps.reduce((s, c) => s + c.sqft, 0) / filteredComps.length) : 0;
  const avgPsf = avgSqft ? avgPrice / avgSqft : 0;

  async function pullComps() {
    setLoading(true);
    setError('');
    try {
      const addr = [deal.property.address, deal.property.city, deal.property.state, deal.property.zip].filter(Boolean).join(', ');
      const result = await fetchComps(addr);
      if (result.ok) {
        const enhancedComps = (result.comps || []).map((c) => ({
          ...c,
          status: 'closed', // AVM comparables are closed/sold properties
        }));
        setComps(enhancedComps);
        update({ analysis: { ...a, comps: enhancedComps } });
      } else {
        setError(result.error || 'Failed to fetch comps');
      }
    } catch (e) {
      setError(e.message);
    }
    setLoading(false);
  }

  const addManualComp = () => {
    const newComp = {
      id: Date.now(),
      address: '',
      city: subjectCity,
      state: deal.property.state || '',
      zip: deal.property.zip || '',
      sqft: 0,
      beds: subjectBeds,
      baths: subjectBaths,
      price: 0,
      dom: 0,
      distance: 0,
      status: 'closed',
      subdivision: subjectSubdivision,
    };
    const updated = [...manualComps, newComp];
    setManualComps(updated);
    update({ analysis: { ...a, manualComps: updated } });
  };

  const updateManualComp = (id, field, value) => {
    const updated = manualComps.map((c) =>
      c.id === id ? { ...c, [field]: value } : c
    );
    setManualComps(updated);
    update({ analysis: { ...a, manualComps: updated } });
  };

  const removeManualComp = (id) => {
    const updated = manualComps.filter((c) => c.id !== id);
    setManualComps(updated);
    update({ analysis: { ...a, manualComps: updated } });
  };

  const allComps = [...filteredComps, ...manualComps.filter((m) => m.status === status)];

  return (
    <div>
      <div className="offer-guidance-box">
        <div className="offer-guidance-title">Comparable Sales & ARV Analysis</div>
        <div className="offer-guidance-copy">Filter properties by size, rooms, and location to determine accurate After-Repair Value (ARV). Subject: {subjectBeds}bd/{subjectBaths}ba, {subjectSqft} sqft</div>
      </div>

      <div className="grid">
        <div className="col span-full">
          <div className="card">
            <div className="card-head"><h3>Pull Comparables</h3></div>
            <div className="card-body">
              <button onClick={pullComps} disabled={loading} style={{ padding: '8px 16px', marginRight: 12 }}>
                {loading ? 'Pulling...' : '↻ Pull Comps from API'}
              </button>
              {error && <div style={{ color: 'red', marginTop: 8 }}>⚠ {error}</div>}
              {comps.length > 0 && <div style={{ marginTop: 8, fontSize: 13, color: '#666' }}>✓ Loaded {comps.length} properties</div>}
            </div>
          </div>
        </div>

        <div className="col">
          <div className="card">
            <div className="card-head"><h3>Filters</h3></div>
            <div className="card-body">
              <div className="frow">
                <div className="frow-label">Sqft Range</div>
                <div className="frow-right">
                  <NumInput value={filters.sqftRange} onChange={(v) => setFilters({ ...filters, sqftRange: v || 0 })} suffix="%" />
                </div>
              </div>
              <div style={{ fontSize: 12, color: '#999', marginBottom: 8 }}>
                Subject {subjectSqft} sqft → {Math.round(subjectSqft * (1 - filters.sqftRange / 100))} – {Math.round(subjectSqft * (1 + filters.sqftRange / 100))} sqft
              </div>

              <div className="frow">
                <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, cursor: 'pointer' }}>
                  <input
                    type="checkbox"
                    checked={filters.exactBeds}
                    onChange={(e) => setFilters({ ...filters, exactBeds: e.target.checked })}
                  />
                  Exact Bedrooms ({subjectBeds}bd)
                </label>
              </div>

              <div className="frow">
                <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, cursor: 'pointer' }}>
                  <input
                    type="checkbox"
                    checked={filters.exactBaths}
                    onChange={(e) => setFilters({ ...filters, exactBaths: e.target.checked })}
                  />
                  Exact Bathrooms ({subjectBaths}ba)
                </label>
              </div>

              {subjectSubdivision && (
                <div className="frow">
                  <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, cursor: 'pointer' }}>
                    <input
                      type="checkbox"
                      checked={filters.subdivision}
                      onChange={(e) => setFilters({ ...filters, subdivision: e.target.checked })}
                    />
                    Same Subdivision ({subjectSubdivision})
                  </label>
                </div>
              )}
            </div>
          </div>
        </div>

        <div className="col">
          <div className="card">
            <div className="card-head"><h3>Statistics</h3></div>
            <div className="card-body">
              <div className="frow"><div className="frow-label">Comps Count</div><div className="in zero">{filteredComps.length}</div></div>
              <div className="frow"><div className="frow-label">Avg Price</div><div className="in zero">{fmtMoney(avgPrice)}</div></div>
              <div className="frow"><div className="frow-label">Avg Sqft</div><div className="in zero">{Math.round(avgSqft).toLocaleString()}</div></div>
              <div className="frow"><div className="frow-label">Avg $/Sqft</div><div className="in zero">{fmtMoney(avgPsf)}</div></div>
              <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid #e0e0e0' }}>
                <div className="frow"><div className="frow-label">Recommended ARV</div><div style={{ fontSize: 16, fontWeight: 700 }}>{fmtMoney(avgPrice)}</div></div>
              </div>
            </div>
          </div>
        </div>

        <div className="col span-full">
          <div style={{ display: 'flex', gap: 8, marginBottom: 12, borderBottom: '1px solid #e0e0e0', paddingBottom: 8 }}>
            {['active', 'closed', 'expired'].map((st) => (
              <button
                key={st}
                onClick={() => setStatus(st)}
                style={{
                  padding: '6px 12px',
                  background: status === st ? '#000' : '#f0f0f0',
                  color: status === st ? '#fff' : '#000',
                  border: 'none',
                  borderRadius: 4,
                  cursor: 'pointer',
                  fontSize: 12,
                  fontWeight: 500,
                }}
              >
                {st === 'active' ? '📍 Active' : st === 'closed' ? '✓ Closed Sales' : '⊘ Expired'}
              </button>
            ))}
          </div>

          <div className="card">
            <div className="card-head">
              <h3>{status === 'active' ? '📍 Active Listings' : status === 'closed' ? '✓ Closed Sales' : '⊘ Expired'}</h3>
              <span className="head-total">{allComps.length} properties</span>
            </div>
            <div className="card-body">
              {allComps.length === 0 ? (
                <div style={{ textAlign: 'center', padding: 24, color: '#999' }}>
                  No {status} properties match filters. {status === 'active' && 'Try broadening your criteria or pulling fresh data.'}
                </div>
              ) : (
                <table className="cmp-tbl" style={{ width: '100%' }}>
                  <thead>
                    <tr>
                      <th>Full Address</th>
                      <th>Subdivision</th>
                      <th style={{ textAlign: 'right', width: 70 }}>Bed/Bath</th>
                      <th style={{ textAlign: 'right', width: 80 }}>Sqft</th>
                      <th style={{ textAlign: 'right', width: 100 }}>Price</th>
                      <th style={{ textAlign: 'right', width: 80 }}>$/Sqft</th>
                      <th style={{ textAlign: 'right', width: 60 }}>DOM</th>
                      <th style={{ textAlign: 'right', width: 60 }}>Distance</th>
                    </tr>
                  </thead>
                  <tbody>
                    {allComps.map((c) => {
                      const parts = [c.address, c.city, c.state, c.zip].filter(Boolean);
                      const fullAddress = parts.join(', ');
                      return (
                        <tr key={c.id || c.mls || c.address}>
                          <td style={{ fontSize: 12 }}>{fullAddress || '—'}</td>
                          <td style={{ fontSize: 12, color: '#666' }}>{c.subdivision || '—'}</td>
                          <td style={{ textAlign: 'right' }}>{c.beds}/{c.baths}</td>
                          <td style={{ textAlign: 'right' }}>{Math.round(c.sqft).toLocaleString()}</td>
                          <td style={{ textAlign: 'right' }}>{fmtMoney(c.price)}</td>
                          <td style={{ textAlign: 'right' }}>{fmtMoney(c.price / Math.max(1, c.sqft))}</td>
                          <td style={{ textAlign: 'right', fontSize: 12 }}>{c.dom || '–'}</td>
                          <td style={{ textAlign: 'right', fontSize: 12 }}>{c.distance ? c.distance.toFixed(1) + 'mi' : '–'}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              )}
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3>Add Manual Comparable</h3></div>
            <div className="card-body">
              <button onClick={addManualComp} style={{ padding: '6px 12px', background: '#f0f0f0', border: 'none', borderRadius: 4, cursor: 'pointer' }}>
                + Add Property
              </button>

              {manualComps.length > 0 && (
                <table className="cmp-tbl" style={{ width: '100%', marginTop: 12 }}>
                  <thead>
                    <tr>
                      <th>Street Address</th>
                      <th style={{ width: 90 }}>City</th>
                      <th style={{ width: 40 }}>ST</th>
                      <th style={{ width: 70 }}>Zip</th>
                      <th style={{ width: 110 }}>Subdivision</th>
                      <th style={{ width: 50 }}>Bd/Ba</th>
                      <th style={{ width: 60 }}>Sqft</th>
                      <th style={{ width: 80 }}>Price</th>
                      <th style={{ width: 40 }}>Status</th>
                      <th style={{ width: 30 }}></th>
                    </tr>
                  </thead>
                  <tbody>
                    {manualComps.map((c) => (
                      <tr key={c.id}>
                        <td><TextInput value={c.address} onChange={(v) => updateManualComp(c.id, 'address', v)} placeholder="123 Main St" /></td>
                        <td style={{ padding: 4 }}><TextInput value={c.city} onChange={(v) => updateManualComp(c.id, 'city', v)} placeholder="City" /></td>
                        <td style={{ padding: 4 }}><TextInput value={c.state} onChange={(v) => updateManualComp(c.id, 'state', v)} placeholder="GA" /></td>
                        <td style={{ padding: 4 }}><TextInput value={c.zip} onChange={(v) => updateManualComp(c.id, 'zip', v)} placeholder="30188" /></td>
                        <td style={{ padding: 4 }}><TextInput value={c.subdivision} onChange={(v) => updateManualComp(c.id, 'subdivision', v)} placeholder="Subdivision" /></td>
                        <td style={{ padding: 4 }}>
                          <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}>
                            <NumInput value={c.beds} onChange={(v) => updateManualComp(c.id, 'beds', v || 0)} />
                            <span style={{ fontSize: 11 }}>/</span>
                            <NumInput value={c.baths} onChange={(v) => updateManualComp(c.id, 'baths', v || 0)} />
                          </span>
                        </td>
                        <td style={{ padding: 4 }}><NumInput value={c.sqft} onChange={(v) => updateManualComp(c.id, 'sqft', v || 0)} /></td>
                        <td style={{ padding: 4 }}><MoneyInput value={c.price} onChange={(v) => updateManualComp(c.id, 'price', v)} /></td>
                        <td style={{ padding: 4 }}>
                          <select
                            value={c.status}
                            onChange={(e) => updateManualComp(c.id, 'status', e.target.value)}
                            style={{ fontSize: 12, padding: '3px 4px', border: '1px solid #ddd', borderRadius: 3 }}
                          >
                            <option value="active">Active</option>
                            <option value="closed">Closed</option>
                            <option value="expired">Expired</option>
                          </select>
                        </td>
                        <td style={{ textAlign: 'center', padding: 4 }}>
                          <button onClick={() => removeManualComp(c.id)} style={{ background: 'none', border: 'none', color: 'red', cursor: 'pointer', fontSize: 16 }}>✕</button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CompsTabAdvanced });
