/* PropertyDetail.jsx — full-screen modal showing one property + booking */

/* Unified money math — MUST match functions/routes/bookingRequests.js computeQuote:
   cleaning = round(subtotal * 0.08), taxes = round(subtotal * 0.07),
   total = subtotal + cleaning + taxes, deposit = round(total * 0.5). */
function pdComputeQuote(rate, nights) {
  const n = Math.max(1, Number(nights) || 1);
  const subtotal = (Number(rate) || 0) * n;
  const cleaning = Math.round(subtotal * 0.08);
  const taxes = Math.round(subtotal * 0.07);
  const total = subtotal + cleaning + taxes;
  const deposit = Math.round(total * 0.5);
  return { nights: n, subtotal, cleaning, taxes, total, deposit };
}

function PropertyDetail({ p, onClose }) {
  const today = new Date().toISOString().slice(0, 10);
  const inThreeDays = new Date(Date.now() + 3 * 86400000).toISOString().slice(0, 10);
  const inWeek = new Date(Date.now() + 7 * 86400000).toISOString().slice(0, 10);
  const params = new URLSearchParams(window.location.search);

  const [checkIn, setCheckIn] = React.useState(params.get('checkIn') || inThreeDays);
  const [checkOut, setCheckOut] = React.useState(params.get('checkOut') || inWeek);
  const [guests, setGuests] = React.useState(parseInt(params.get('guests') || '4', 10) || 4);
  const [confirmed, setConfirmed] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');
  const [serverQuote, setServerQuote] = React.useState(null);

  // Guard against malformed/invalid date params so the quote never renders NaN
  // and the request can't be submitted with bad dates.
  const _ci = new Date(checkIn), _co = new Date(checkOut);
  const validDates = !isNaN(_ci.getTime()) && !isNaN(_co.getTime()) && _co > _ci;
  const nights = validDates ? Math.max(1, Math.ceil((_co - _ci) / 86400000)) : 0;
  const localQuote = pdComputeQuote(p.rate, validDates ? nights : 1);
  const quote = serverQuote || localQuote;
  const total = quote.subtotal;
  const fee = quote.cleaning;
  const tax = quote.taxes;
  const grand = quote.total;
  const deposit = quote.deposit != null ? quote.deposit : Math.round(grand * 0.5);

  // Request-to-book: submit the request through the integration layer.
  // Live mode → Firebase Functions (Hospitable + Stripe deposit on host approval);
  //             the server returns the authoritative quote, which we display.
  // Demo mode → logged to localStorage so the static site stays end-to-end.
  async function handleReserve() {
    if (submitting || !validDates) return;
    setError('');
    setSubmitting(true);
    try {
      if (window.NovusAPI) {
        const resp = await window.NovusAPI.createBookingRequest({
          listingId: p.hospitableId || null,
          propertyId: p.id,
          propertyName: p.name,
          checkIn,
          checkOut,
          guests: Number(guests) || 1,
          fallbackNightly: p.rate,
          guest: {},
        });
        if (resp && resp.quote) setServerQuote(resp.quote);
      }
      setConfirmed(true);
    } catch (e) {
      console.error('Booking request failed:', e);
      setError(e.message || 'Could not send your request. Please try again.');
    } finally {
      setSubmitting(false);
    }
  }

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  if (confirmed) {
    return (
      <div className="modal-scrim" onClick={onClose}>
        <div className="modal-sheet" onClick={e => e.stopPropagation()}
             style={{ maxWidth: 560, padding: 56, textAlign: 'center' }}>
          <span className="sun-bullet" style={{ width: 32, height: 32, margin: '0 auto 24px' }} />
          <h2 style={{
            fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 36,
            color: 'var(--navy-900)', margin: '0 0 12px', letterSpacing: '-0.01em',
          }}>Request received.</h2>
          <p style={{ color: 'var(--ink-700)', fontSize: 16, lineHeight: 1.6, margin: '0 0 8px' }}>
            <strong>{p.name}</strong>, {p.neighborhood}.<br/>
            Your host will confirm shortly and send a secure link for the
            {' '}50% deposit (${deposit.toLocaleString()}). No charge until you pay it.
          </p>
          <p style={{
            fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 20,
            color: 'var(--navy-700)', margin: '20px 0 32px',
          }}>Nos vemos pronto.</p>
          <button className="btn btn-primary" onClick={onClose}>Back to residences</button>
        </div>
      </div>
    );
  }

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal-sheet" onClick={e => e.stopPropagation()}>
        <button onClick={onClose} aria-label="close" style={{
          position: 'absolute', right: 20, top: 20, zIndex: 3,
          width: 40, height: 40, borderRadius: 999, border: 0,
          background: 'rgba(255,255,255,0.95)', cursor: 'pointer',
          color: 'var(--navy-900)', fontSize: 18,
        }}>×</button>

        {/* Hero photo */}
        <div style={{ position: 'relative', aspectRatio: '16/9', background: 'var(--sand-100)' }}>
          <img src={p.photo} alt={p.name}
               style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(180deg, rgba(15,42,66,0) 50%, rgba(15,42,66,0.55) 100%)',
          }}/>
          <div style={{ position: 'absolute', left: 32, bottom: 24, color: '#fff' }}>
            <div className="overline" style={{ color: 'rgba(255,255,255,0.85)', marginBottom: 8 }}>{p.neighborhood}</div>
            <h2 style={{
              fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 48,
              margin: 0, color: '#fff', letterSpacing: '-0.01em', lineHeight: 1.1,
            }}>{p.name}</h2>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 48, padding: 40 }}>
          <div>
            <p style={{
              fontFamily: 'var(--font-display)', fontStyle: 'italic',
              fontSize: 22, color: 'var(--navy-900)', lineHeight: 1.5,
              margin: '0 0 28px', textWrap: 'pretty',
            }}>{p.tagline}</p>

            <hr className="horizon-rule" style={{ marginBottom: 24 }} />

            <div className="overline" style={{ marginBottom: 12 }}>Inside</div>
            <ul style={{
              listStyle: 'none', padding: 0, margin: 0,
              display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10,
            }}>
              {p.facts.map(f => (
                <li key={f} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  fontSize: 14, color: 'var(--ink-700)',
                }}>
                  <span style={{
                    width: 6, height: 6, borderRadius: 999, background: 'var(--sun-coral)',
                  }}/>{f}
                </li>
              ))}
            </ul>

            <div className="overline" style={{ marginTop: 32, marginBottom: 12 }}>Available on</div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {['Direct', 'Airbnb', 'VRBO', 'Booking.com'].map(c => (
                <span key={c} style={{
                  padding: '6px 14px', border: '1px solid var(--horizon-200)',
                  borderRadius: 999, fontSize: 12, color: 'var(--navy-700)', fontWeight: 500,
                }}>{c}</span>
              ))}
            </div>
          </div>

          {/* Booking card */}
          <aside style={{
            background: 'var(--sand-50)', border: '1px solid var(--line)',
            borderRadius: 18, padding: 28, position: 'sticky', top: 24, height: 'fit-content',
          }}>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
              <div style={{
                fontFamily: 'var(--font-text)', fontFeatureSettings: '"tnum"',
                fontSize: 28, fontWeight: 500, color: 'var(--navy-900)',
              }}>${p.rate.toLocaleString()}<span style={{
                fontSize: 13, color: 'var(--ink-500)', fontWeight: 400,
              }}> / night</span></div>
              <div style={{ fontSize: 12, color: 'var(--ink-500)' }}>★ {p.rating} · {p.reviews}</div>
            </div>

            <hr style={{ border: 0, height: 1, background: 'var(--horizon-200)', opacity: 0.5, margin: '20px 0' }} />

            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8,
              border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden',
              background: '#fff',
            }}>
              <DateField label="Check in" value={checkIn} setValue={setCheckIn} type="date" min={today} />
              <DateField label="Check out" value={checkOut} setValue={setCheckOut} type="date" min={checkIn} borderLeft />
              <div style={{ gridColumn: '1 / -1', borderTop: '1px solid var(--line)', padding: '10px 14px' }}>
                <div style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)', fontWeight: 600 }}>Guests</div>
                <input value={guests} onChange={e => setGuests(e.target.value)}
                  style={{ border: 0, outline: 'none', background: 'transparent', width: '100%', padding: 0, marginTop: 2, fontSize: 14, color: 'var(--navy-900)' }} />
              </div>
            </div>

            {validDates && (
              <div style={{ marginTop: 20, display: 'grid', gap: 8, fontSize: 14 }}>
                <Row label={`$${p.rate.toLocaleString()} × ${nights} nights`} value={`$${total.toLocaleString()}`} />
                <Row label="Cleaning & service" value={`$${fee.toLocaleString()}`} />
                <Row label="Taxes" value={`$${tax.toLocaleString()}`} />
                <hr style={{ border: 0, height: 1, background: 'var(--line)', margin: '8px 0' }} />
                <Row label={<strong style={{ color: 'var(--navy-900)' }}>Total</strong>} value={<strong style={{ color: 'var(--navy-900)', fontFeatureSettings: '"tnum"' }}>${grand.toLocaleString()}</strong>} />
              </div>
            )}

            <button className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', marginTop: 20, padding: '16px', opacity: (submitting || !validDates) ? 0.7 : 1 }}
                    disabled={submitting || !validDates}
                    onClick={handleReserve}>
              {submitting ? 'Sending request…' : 'Request to book · nos vemos pronto'}
            </button>
            {!validDates && (
              <div style={{ marginTop: 12, fontSize: 13, color: 'var(--ink-500)', textAlign: 'center' }}>
                Select valid check-in and check-out dates.
              </div>
            )}
            {error && (
              <div role="alert" style={{ marginTop: 12, fontSize: 13, color: '#b4231f', textAlign: 'center' }}>
                {error}
              </div>
            )}
            <div style={{ textAlign: 'center', marginTop: 12, fontSize: 12, color: 'var(--ink-500)' }}>
              You won't be charged yet — your host confirms, then a secure
              {' '}<strong style={{ color: 'var(--navy-700)' }}>50% deposit</strong> link is sent.
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

function DateField({ label, value, setValue, borderLeft, type, min }) {
  return (
    <label style={{ padding: '10px 14px', borderLeft: borderLeft ? '1px solid var(--line)' : 0, cursor: 'text' }}>
      <div style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)', fontWeight: 600 }}>{label}</div>
      <input value={value} onChange={e => setValue(e.target.value)} type={type || 'text'} min={min}
        style={{ border: 0, outline: 'none', background: 'transparent', width: '100%', padding: 0, marginTop: 2, fontSize: 14, color: 'var(--navy-900)', fontFeatureSettings: '"tnum"' }} />
    </label>
  );
}

function Row({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', color: 'var(--ink-700)' }}>
      <span>{label}</span><span style={{ fontFeatureSettings: '"tnum"' }}>{value}</span>
    </div>
  );
}

window.PropertyDetail = PropertyDetail;
