// Marsan Extras — Tools (EMI, Compare, Saved Searches)

const ToolsPage = () => {
  if (window.MarsanMobile && window.MarsanMobile.isMobile && window.MarsanMobile.isMobile()) {
    return <window.MarsanMobile.Tools />;
  }
  const C = window.MarsanComponents;
  const { Icon } = C;
  const { PROPERTIES } = window.MARSAN_DATA;

  const initLoan = (() => {
    const p = new URLSearchParams(window.location.search).get('loan');
    const n = p ? Math.max(10, Math.min(500, parseInt(p, 10))) : 75;
    return Number.isFinite(n) ? n : 75;
  })();
  const [loanAmt, setLoanAmt] = React.useState(initLoan);
  const [tenure, setTenure] = React.useState(20);
  const [rate, setRate] = React.useState(8.5);
  const [compareIds, setCompareIds] = React.useState([]);
  const [savedSearches, setSavedSearches] = React.useState([]);
  const [prefsLoaded, setPrefsLoaded] = React.useState(false);
  const DEFAULT_SEARCHES = [
    { t: 'East-facing plots in Shadnagar', f: 'Open Plots · ₹50L–1Cr · East', n: 4, on: true },
    { t: 'Villas under ₹5Cr', f: 'Villas · Hyderabad · Ready to move', n: 2, on: true },
    { t: 'Commercial · Airport corridor', f: 'Commercial · ₹1Cr+', n: 0, on: false },
  ];

  // Load prefs from Redis (server) once on mount.
  React.useEffect(() => {
    let alive = true;
    (async () => {
      const [storedSearches, storedCompare] = await Promise.all([
        window.MarsanAPI.prefs.get('saved-searches').catch(() => null),
        window.MarsanAPI.prefs.get('compare').catch(() => null),
      ]);
      if (!alive) return;
      setSavedSearches(Array.isArray(storedSearches) ? storedSearches : DEFAULT_SEARCHES);
      setCompareIds(Array.isArray(storedCompare) ? storedCompare : []);
      setPrefsLoaded(true);
    })();
    return () => { alive = false; };
  }, []);

  // Debounced server-side persist (don't fire until prefs have loaded).
  React.useEffect(() => {
    if (!prefsLoaded) return;
    const t = setTimeout(() => { window.MarsanAPI.prefs.set('saved-searches', savedSearches).catch(() => {}); }, 400);
    return () => clearTimeout(t);
  }, [savedSearches, prefsLoaded]);
  React.useEffect(() => {
    if (!prefsLoaded) return;
    const t = setTimeout(() => { window.MarsanAPI.prefs.set('compare', compareIds).catch(() => {}); }, 400);
    return () => clearTimeout(t);
  }, [compareIds, prefsLoaded]);

  const P = loanAmt * 100000;
  const r = rate / 12 / 100;
  const n = tenure * 12;
  const emi = (P * r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) - 1);
  const total = emi * n;
  const interest = total - P;

  // Auto-format ₹: stays in Lakhs below 100, switches to Cr at and above.
  const formatLakhs = (lakhs) => {
    if (lakhs >= 100) {
      const cr = lakhs / 100;
      return `₹${cr % 1 === 0 ? cr : cr.toFixed(2).replace(/\.?0+$/, '')}Cr`;
    }
    return `₹${lakhs % 1 === 0 ? lakhs : lakhs.toFixed(1)}L`;
  };
  const formatRupees = (rupees) => formatLakhs(rupees / 100000);

  // After prefs load, if there's nothing yet, default the compare to the first 3 properties.
  React.useEffect(() => {
    if (prefsLoaded && PROPERTIES.length && !compareIds.length) {
      setCompareIds(PROPERTIES.slice(0, 3).map(p => p.id));
    }
  }, [PROPERTIES.length, prefsLoaded]);

  const removeSearch = (i) => setSavedSearches(arr => arr.filter((_, j) => j !== i));
  const toggleSearch = (i) => setSavedSearches(arr => arr.map((s, j) => j === i ? { ...s, on: !s.on } : s));
  const addSearch = () => {
    const t = prompt('Name your search:');
    if (!t) return;
    setSavedSearches(arr => [...arr, { t, f: 'Custom criteria', n: 0, on: true }]);
  };

  const compareList = compareIds.map(id => PROPERTIES.find(p => p.id === id)).filter(Boolean);

  const removeCompare = (id) => setCompareIds(c => c.filter(x => x !== id));

  return (
    <div className="ms-root" style={{ width: '100%', minHeight: '100vh', background: '#f6f1e6' }}>
      <C.Header active="" light={false} />
      <section style={{ padding: '40px 56px' }}>
        <div className="ms-eyebrow" style={{ marginBottom: 8 }}>Tools & investor utilities</div>
        <h1 className="ms-h1" style={{ fontFamily: 'Cormorant Garamond, serif', fontWeight: 300, fontSize: 56, color: '#0a1f17', margin: '0 0 8px', lineHeight: 1.05 }}>EMI · Compare · Saved searches.</h1>
        <p style={{ color: '#8c857b', margin: '0 0 40px', maxWidth: 600 }}>Self-serve tools to plan a purchase, compare assets, and stay in touch with new launches.</p>

        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 24 }} className="ms-collapse-mobile">
          {/* EMI */}
          <div style={{ background: '#0a1f17', color: '#e8dcc1', padding: 40, position: 'relative' }} className="ms-grain">
            <div className="ms-eyebrow on-dark" style={{ marginBottom: 12, position: 'relative' }}>EMI calculator</div>
            <h3 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 32, color: '#f6f1e6', margin: '0 0 32px', position: 'relative' }}>Plan your home loan.</h3>

            <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }} className="ms-collapse-mobile">
              <div>
                <div style={{ marginBottom: 24 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                    <span className="ms-label on-dark">Loan Amount</span>
                    <span style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 20, color: '#e2bd6b' }}>{formatLakhs(loanAmt)}</span>
                  </div>
                  <input type="range" min="10" max="500" value={loanAmt} onChange={(e) => setLoanAmt(+e.target.value)} style={{ width: '100%' }} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'rgba(232,220,193,0.5)', marginTop: 4 }}>
                    <span>₹10L</span><span>₹5Cr</span>
                  </div>
                </div>
                <div style={{ marginBottom: 24 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                    <span className="ms-label on-dark">Tenure</span>
                    <span style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 20, color: '#e2bd6b' }}>{tenure} yrs</span>
                  </div>
                  <input type="range" min="5" max="30" value={tenure} onChange={(e) => setTenure(+e.target.value)} style={{ width: '100%' }} />
                </div>
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                    <span className="ms-label on-dark">Interest Rate</span>
                    <span style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 20, color: '#e2bd6b' }}>{rate}%</span>
                  </div>
                  <input type="range" min="6" max="14" step="0.1" value={rate} onChange={(e) => setRate(+e.target.value)} style={{ width: '100%' }} />
                </div>
              </div>
              <div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(201,165,92,0.3)', padding: 28 }}>
                <div className="ms-meta" style={{ color: 'rgba(232,220,193,0.6)' }}>MONTHLY EMI</div>
                <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 44, color: '#e2bd6b', margin: '8px 0 24px', lineHeight: 1 }}>
                  ₹{Math.round(emi).toLocaleString('en-IN')}
                </div>
                <div style={{ height: 1, background: 'rgba(232,220,193,0.15)', marginBottom: 20 }} />
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                    <span style={{ color: 'rgba(232,220,193,0.65)' }}>Principal</span>
                    <span style={{ color: '#f6f1e6' }}>{formatRupees(P)}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                    <span style={{ color: 'rgba(232,220,193,0.65)' }}>Total Interest</span>
                    <span style={{ color: '#c9a55c' }}>{formatRupees(interest)}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                    <span style={{ color: 'rgba(232,220,193,0.65)' }}>Total Payable</span>
                    <span style={{ color: '#f6f1e6', fontWeight: 600 }}>{formatRupees(total)}</span>
                  </div>
                </div>
                <div style={{ marginTop: 24, height: 6, background: 'rgba(232,220,193,0.1)', display: 'flex', overflow: 'hidden' }}>
                  <div style={{ width: `${(P / total) * 100}%`, background: '#e2bd6b', transition: 'width 0.3s' }} />
                  <div style={{ flex: 1, background: '#c9a55c', opacity: 0.5 }} />
                </div>
              </div>
            </div>
            <a href="/enquire.html?type=callback" className="ms-btn ms-btn-primary" style={{ marginTop: 32, position: 'relative' }}>
              Talk to a Loan Partner <Icon name="arrow" size={14} />
            </a>
          </div>

          {/* Saved Searches */}
          <div style={{ background: '#fff', border: '1px solid #d9cfb8', padding: 40 }}>
            <div className="ms-eyebrow" style={{ marginBottom: 12 }}>Saved searches</div>
            <h3 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 28, color: '#0a1f17', margin: '0 0 24px' }}>Get notified when matches arrive.</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {savedSearches.map((s, i) => (
                <div key={i} style={{ padding: 16, border: '1px solid #d9cfb8', background: '#f6f1e6' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 18, color: '#0a1f17' }}>{s.t}</div>
                      <div style={{ fontSize: 11, color: '#8c857b', marginTop: 4 }}>{s.f}</div>
                    </div>
                    {s.n > 0 && <span className="ms-chip gold" style={{ fontSize: 9 }}>{s.n} new</span>}
                    <button onClick={() => removeSearch(i)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#a88841', fontSize: 16, marginLeft: 8 }}>×</button>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14, paddingTop: 12, borderTop: '1px solid #d9cfb8' }}>
                    <div style={{ display: 'flex', gap: 16, fontSize: 11, color: '#8c857b' }}>
                      <span style={{ display: 'flex', gap: 4, alignItems: 'center' }}><Icon name="mail" size={11} /> Email</span>
                      <span style={{ display: 'flex', gap: 4, alignItems: 'center' }}><Icon name="whatsapp" size={11} /> WhatsApp</span>
                    </div>
                    <button onClick={() => toggleSearch(i)} aria-label={`Toggle ${s.t}`}
                      style={{ width: 32, height: 18, borderRadius: 9, background: s.on ? '#c9a55c' : '#d9cfb8', position: 'relative', cursor: 'pointer', border: 'none' }}>
                      <div style={{ position: 'absolute', top: 2, left: s.on ? 16 : 2, width: 14, height: 14, borderRadius: '50%', background: '#fff', transition: 'all 0.2s' }} />
                    </button>
                  </div>
                </div>
              ))}
              {savedSearches.length === 0 && <div style={{ textAlign: 'center', padding: 24, color: '#8c857b', fontSize: 13 }}>No saved searches yet.</div>}
            </div>
            <button onClick={addSearch} className="ms-btn ms-btn-ghost-dark ms-btn-sm" style={{ width: '100%', marginTop: 16 }}>
              <Icon name="plus" size={12} /> Create New Alert
            </button>
          </div>
        </div>

        {/* COMPARE */}
        <div style={{ marginTop: 40, background: '#efe8d8', padding: 40, border: '1px solid #d9cfb8' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 24 }}>
            <div>
              <div className="ms-eyebrow" style={{ marginBottom: 8 }}>Compare</div>
              <h3 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 28, color: '#0a1f17', margin: 0 }}>Side-by-side property comparison.</h3>
            </div>
            <span className="ms-meta">{compareList.length} / 4 SELECTED</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: `180px repeat(${compareList.length}, 1fr)${compareList.length < 4 ? ' 200px' : ''}`, background: '#fff', border: '1px solid #d9cfb8', overflowX: 'auto' }}>
            <div style={{ padding: 20, borderBottom: '1px solid #d9cfb8' }} />
            {compareList.map(p => (
              <div key={p.id} style={{ padding: 20, borderLeft: '1px solid #d9cfb8', borderBottom: '1px solid #d9cfb8', position: 'relative' }}>
                <button onClick={() => removeCompare(p.id)} style={{ position: 'absolute', top: 8, right: 8, background: 'none', border: 'none', cursor: 'pointer', color: '#a88841' }}>×</button>
                <div className="ms-img-ph" style={{ height: 120, marginBottom: 12 }}><span style={{ fontSize: 9 }}>{p.image}</span></div>
                <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 18, color: '#0a1f17' }}>{p.name}</div>
                <div style={{ fontSize: 11, color: '#8c857b', marginTop: 2 }}>{p.location}</div>
              </div>
            ))}
            {compareList.length < 4 && (
              <div style={{ padding: 20, borderLeft: '1px solid #d9cfb8', borderBottom: '1px solid #d9cfb8', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: '#a88841' }}>
                <div style={{ width: 56, height: 56, border: '2px dashed #c9a55c', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 8 }}>
                  <Icon name="plus" size={20} />
                </div>
                <select onChange={(e) => { if (e.target.value) setCompareIds(c => [...c, e.target.value]); }}
                  style={{ background: 'transparent', border: 'none', color: '#a88841', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', cursor: 'pointer' }}>
                  <option value="">Add property</option>
                  {PROPERTIES.filter(p => !compareIds.includes(p.id)).map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
              </div>
            )}

            {[
              { l: 'Price', f: p => `₹${p.priceMin}–${p.priceMax} ${p.priceUnit}` },
              { l: 'Area', f: p => `${p.areaMin}–${p.areaMax} ${p.areaUnit}` },
              { l: 'Status', f: p => p.status },
              { l: 'RERA', f: p => p.rera || '—' },
              { l: 'Possession', f: p => p.launch },
              { l: 'Highlight', f: p => p.highlight || '—' },
            ].map((row, i, arr) => (
              <React.Fragment key={row.l}>
                <div style={{ padding: '14px 20px', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#8c857b', borderBottom: i < arr.length - 1 ? '1px solid #efe8d8' : 'none', background: '#fafafa' }}>{row.l}</div>
                {compareList.map(p => (
                  <div key={p.id} style={{ padding: '14px 20px', fontSize: 13, color: '#0a1f17', borderLeft: '1px solid #d9cfb8', borderBottom: i < arr.length - 1 ? '1px solid #efe8d8' : 'none' }}>{row.f(p)}</div>
                ))}
                {compareList.length < 4 && <div style={{ borderLeft: '1px solid #d9cfb8', borderBottom: i < arr.length - 1 ? '1px solid #efe8d8' : 'none' }} />}
              </React.Fragment>
            ))}
          </div>
        </div>
      </section>
      <C.Footer />
    </div>
  );
};

window.ToolsPage = ToolsPage;
