// Modals + Tweaks
function Modal({ open, onClose, children, maxW = 680 }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(26,26,23,0.66)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 200, padding: 20, animation: 'svFadeIn 240ms var(--ease-out)' }} onClick={onClose}>
      <div style={{ background: 'var(--linen)', borderRadius: 6, width: '100%', maxWidth: maxW, maxHeight: '90vh', overflow: 'auto', position: 'relative', boxShadow: '0 32px 64px rgba(0,0,0,0.3)', animation: 'svSlideUp 300ms var(--ease-out)' }} onClick={e => e.stopPropagation()}>
        <button style={{ position: 'absolute', top: 16, right: 16, width: 36, height: 36, borderRadius: '50%', border: 0, background: 'rgba(26,26,23,0.08)', color: 'var(--night-owl)', fontSize: 22, cursor: 'pointer', zIndex: 2 }} onClick={onClose} aria-label="Close">×</button>
        {children}
      </div>
    </div>
  );
}

function InquiryModal({ open, onClose }) {
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({ address: '', units: 1, type: 'single', horizon: 'unsure', value: 450000, name: '', email: '', phone: '', notes: '' });
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  React.useEffect(() => { if (open) { setStep(0); setError(null); setSubmitting(false); } }, [open]);
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const submit = async () => {
    setSubmitting(true);
    setError(null);
    try {
      const id = window.SV_FORMSPREE_ID;
      if (id) {
        const res = await fetch('https://formspree.io/f/' + id, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
          body: JSON.stringify({
            _subject: 'New Sovana inquiry · portfolio analysis',
            source: 'inquiry-modal',
            name: form.name,
            email: form.email,
            phone: form.phone,
            address: form.address,
            property_type: form.type,
            horizon: form.horizon,
            estimated_value: '$' + form.value.toLocaleString(),
            notes: form.notes,
          }),
        });
        if (!res.ok) throw new Error('HTTP ' + res.status);
      } else {
        console.warn('[Sovana] SV_FORMSPREE_ID not set in index.html — inquiry submission is mocked. Sign up at formspree.io to enable real delivery.');
      }
      setStep(3);
    } catch (err) {
      setError('Something went wrong. Please try again, or email hello@sovanapm.com directly.');
    } finally {
      setSubmitting(false);
    }
  };
  const inp = { width: '100%', padding: '14px 16px', borderRadius: 6, border: '1.5px solid var(--sandstone)', background: 'var(--cream)', fontFamily: 'var(--font-sans)', fontSize: 15, color: 'var(--night-owl)', outline: 'none', boxSizing: 'border-box' };
  const lbl = { fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--dusk)', marginBottom: 8, display: 'block' };
  return (
    <Modal open={open} onClose={onClose} maxW={640}>
      <div style={{ padding: '44px 40px 20px', borderBottom: '1px solid var(--sandstone)' }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', fontWeight: 600, color: 'var(--sovana-gold)', textTransform: 'uppercase' }}>// FREE PORTFOLIO ANALYSIS · STEP {Math.min(step + 1, 3)} / 3</div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 38, lineHeight: 1.1, letterSpacing: '-0.01em', margin: '14px 0 22px', color: 'var(--night-owl)' }}>
          {step === 0 && 'Tell us about the asset.'}
          {step === 1 && 'Which horizon are you considering?'}
          {step === 2 && 'Where should we write back?'}
          {step === 3 && (<>Request received. <em style={{ color: 'var(--sovana-gold)', fontStyle: 'italic' }}>We'll be in touch</em>.</>)}
        </h2>
        {step < 3 && <div style={{ display: 'flex', gap: 6 }}>{[0,1,2].map(i => <div key={i} style={{ height: 3, borderRadius: 2, background: i <= step ? 'var(--sovana-gold)' : 'var(--sandstone)', flex: 1 }} />)}</div>}
      </div>
      <div style={{ padding: '28px 40px 20px' }}>
        {step === 0 && <>
          <label style={{ display: 'block', marginBottom: 22 }}><span style={lbl}>Property address</span><input style={inp} placeholder="2134 W Homer St, Chicago, IL 60647" value={form.address} onChange={e => update('address', e.target.value)} /></label>
          <label style={{ display: 'block', marginBottom: 22 }}><span style={lbl}>Property type</span>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {[['single','Single-family'],['condo','Condo / apt'],['multi','Multi-unit'],['portfolio','Portfolio (2+ units)']].map(([k,l]) => (
                <button key={k} style={{ padding: '10px 16px', borderRadius: 6, border: '1.5px solid var(--night-owl)', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 13, cursor: 'pointer', background: form.type === k ? 'var(--night-owl)' : 'transparent', color: form.type === k ? 'var(--cream)' : 'var(--night-owl)' }} onClick={() => update('type', k)}>{l}</button>
              ))}
            </div>
          </label>
          <label style={{ display: 'block', marginBottom: 22 }}><span style={lbl}>Estimated value · ${form.value.toLocaleString()}</span><input type="range" min="200000" max="5000000" step="25000" value={form.value} onChange={e => update('value', +e.target.value)} style={{ width: '100%', accentColor: '#C4A265' }} /></label>
        </>}
        {step === 1 && <>
          {[['long','Long Term (12+ month)','Stable, predictable income. Lowest operational load.'],['mid','Mid Term (1 to 6 month)','Furnished premium rates for corporate & healthcare demand.'],['short','Short Term (nightly / weekly)','Highest yield. Dynamic pricing, full hospitality layer.'],['unsure','Not sure. Recommend','We walk the asset and return a side by side projection.']].map(([k,l,d]) => (
            <button key={k} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '18px 20px', borderRadius: 6, marginBottom: 10, cursor: 'pointer', border: `1.5px solid ${form.horizon === k ? 'var(--sovana-gold)' : 'var(--sandstone)'}`, background: form.horizon === k ? 'var(--linen)' : 'var(--cream)' }} onClick={() => update('horizon', k)}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, color: 'var(--night-owl)', letterSpacing: '-0.01em' }}>{l}</div>
                <div style={{ width: 20, height: 20, borderRadius: '50%', border: `1.5px solid ${form.horizon === k ? 'var(--sovana-gold)' : 'var(--sandstone)'}`, background: form.horizon === k ? 'var(--sovana-gold)' : 'transparent' }} />
              </div>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--dusk)', marginTop: 4, lineHeight: 1.5 }}>{d}</div>
            </button>
          ))}
        </>}
        {step === 2 && <>
          <label style={{ display: 'block', marginBottom: 22 }}><span style={lbl}>Your name</span><input style={inp} value={form.name} onChange={e => update('name', e.target.value)} placeholder="Marcus Thompson" /></label>
          <label style={{ display: 'block', marginBottom: 22 }}><span style={lbl}>Email</span><input style={inp} type="email" value={form.email} onChange={e => update('email', e.target.value)} placeholder="you@domain.com" /></label>
          <label style={{ display: 'block', marginBottom: 22 }}><span style={lbl}>Phone (optional)</span><input style={inp} value={form.phone} onChange={e => update('phone', e.target.value)} placeholder="+1 312 555 0112" /></label>
          <label style={{ display: 'block', marginBottom: 22 }}><span style={lbl}>Anything else?</span><textarea style={{ ...inp, minHeight: 80, resize: 'vertical' }} value={form.notes} onChange={e => update('notes', e.target.value)} placeholder="Current PM, target yield, timing, concerns…" /></label>
        </>}
        {step === 3 && <div style={{ textAlign: 'center', padding: '12px 0 8px' }}>
          <div style={{ width: 140, height: 140, borderRadius: '50%', border: '1.5px solid var(--sovana-gold)', margin: '0 auto 24px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="36" height="26" viewBox="0 0 36 26" fill="none"><path d="M3 13 L14 24 L33 4" stroke="var(--sovana-gold)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
          </div>
          <p style={{ fontFamily: 'var(--font-sans)', fontSize: 16, color: 'var(--dusk)', margin: '0 auto 24px', maxWidth: 440, lineHeight: 1.6 }}>A Sovana principal will walk {form.address || 'the asset'} within the week and return a side by side projection across all three strategies.</p>
          <div style={{ textAlign: 'left', padding: '20px 22px', background: 'var(--cream)', border: '1px solid var(--sandstone)', borderRadius: 6, maxWidth: 460, margin: '0 auto' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', color: 'var(--sovana-gold)', fontWeight: 600, textTransform: 'uppercase' }}>// Your request</div>
            <div style={{ marginTop: 10, fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--night-owl)', lineHeight: 1.9 }}>
              <div><span style={{ color: 'var(--dusk)' }}>address</span> · {form.address || ' '}</div>
              <div><span style={{ color: 'var(--dusk)' }}>horizon</span> · {form.horizon}</div>
              <div><span style={{ color: 'var(--dusk)' }}>value.est</span> · ${form.value.toLocaleString()}</div>
              <div><span style={{ color: 'var(--dusk)' }}>reply.to</span> · {form.email || ' '}</div>
            </div>
          </div>
        </div>}
      </div>
      {error && step === 2 && <div style={{ margin: '0 40px 8px', padding: '12px 14px', background: 'rgba(182,65,65,0.08)', border: '1px solid rgba(182,65,65,0.35)', borderRadius: 4, fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--danger)' }}>{error}</div>}
      <div style={{ padding: '20px 40px 32px', display: 'flex', alignItems: 'center', gap: 12 }}>
        {step > 0 && step < 3 && <button disabled={submitting} style={{ background: 'transparent', border: 0, color: 'var(--dusk)', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 13, cursor: submitting ? 'not-allowed' : 'pointer', opacity: submitting ? 0.5 : 1 }} onClick={() => setStep(s => s - 1)}>← Back</button>}
        <div style={{ flex: 1 }} />
        {step < 2 && <button style={{ background: 'var(--sovana-teal)', color: 'var(--cream)', border: 0, padding: '14px 24px', borderRadius: 6, fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', cursor: 'pointer' }} onClick={() => setStep(s => s + 1)}>Continue →</button>}
        {step === 2 && <button disabled={submitting} style={{ background: 'var(--sovana-gold)', color: 'var(--obsidian)', border: 0, padding: '14px 24px', borderRadius: 6, fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', cursor: submitting ? 'not-allowed' : 'pointer', opacity: submitting ? 0.6 : 1 }} onClick={submit}>{submitting ? 'Sending...' : 'Send request'}</button>}
        {step === 3 && <button style={{ background: 'var(--sovana-teal)', color: 'var(--cream)', border: 0, padding: '14px 24px', borderRadius: 6, fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', cursor: 'pointer' }} onClick={onClose}>Close</button>}
      </div>
    </Modal>
  );
}

function PropertyModal({ property, onClose }) {
  if (!property) return null;
  return (
    <Modal open={!!property} onClose={onClose} maxW={900}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr' }} className="sv-grid-collapse">
        <div style={{ position: 'relative', minHeight: 420 }}>
          <img src={property.img} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
          <div style={{ position: 'absolute', left: 20, top: 20, padding: '6px 12px', background: 'rgba(26,26,23,0.75)', color: 'var(--sovana-gold)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', fontWeight: 600, textTransform: 'uppercase', borderRadius: 2 }}>// {property.tag}</div>
        </div>
        <div style={{ padding: '40px 36px' }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', fontWeight: 600, color: 'var(--sovana-gold)', textTransform: 'uppercase' }}>// {property.num} · {property.eye}</div>
          <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 40, lineHeight: 1.1, margin: '10px 0 18px', color: 'var(--night-owl)', letterSpacing: '-0.01em' }}>{property.title}</h3>
          <p style={{ fontFamily: 'var(--font-sans)', fontSize: 15, lineHeight: 1.65, color: 'var(--dusk)' }}>{property.body}</p>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, margin: '24px 0', padding: '20px 0', borderTop: '1px solid var(--sandstone)', borderBottom: '1px solid var(--sandstone)' }}>
            <div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', fontWeight: 600, color: 'var(--tuscan-earth)', textTransform: 'uppercase', marginBottom: 4 }}>Yield profile</div><div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 22, fontWeight: 500, color: 'var(--sovana-gold)', letterSpacing: '-0.01em' }}>{property.uplift}</div></div>
            <div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', fontWeight: 600, color: 'var(--tuscan-earth)', textTransform: 'uppercase', marginBottom: 4 }}>Ideal for</div><div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, color: 'var(--night-owl)', letterSpacing: '-0.01em' }}>{property.count}</div></div>
          </div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
            {property.points.map((p, i) => (
              <li key={i} style={{ fontFamily: 'var(--font-sans)', fontSize: 14, padding: '9px 0', display: 'flex', gap: 12, alignItems: 'center', color: 'var(--night-owl)' }}>
                <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--sovana-gold)' }}>→</span>
                {p}
              </li>
            ))}
          </ul>
        </div>
      </div>
    </Modal>
  );
}

function TweaksPanel({ active, state, setState }) {
  if (!active) return null;
  const { theme, heroVariant, accent, ornaments, headline } = state;
  const apply = (patch) => { const next = { ...state, ...patch }; setState(next); window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*'); };
  const seg = (options, value, onChange) => (
    <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
      {options.map(([k, l]) => (
        <button key={String(k)} onClick={() => onChange(k)} style={{ flex: 1, padding: '8px 10px', borderRadius: 4, border: '1px solid', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 11, letterSpacing: '0.05em', cursor: 'pointer', minWidth: 60, background: value === k ? 'var(--night-owl)' : 'transparent', color: value === k ? 'var(--cream)' : 'var(--night-owl)', borderColor: value === k ? 'var(--night-owl)' : 'var(--sandstone)' }}>{l}</button>
      ))}
    </div>
  );
  const lbl = { fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', fontWeight: 600, textTransform: 'uppercase', color: 'var(--dusk)', marginBottom: 8 };
  const inp = { width: '100%', padding: '8px 10px', borderRadius: 4, border: '1px solid var(--sandstone)', fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--night-owl)', background: 'var(--cream)', outline: 'none', boxSizing: 'border-box' };
  return (
    <div style={{ position: 'fixed', right: 20, bottom: 20, width: 300, background: 'var(--linen)', border: '1px solid var(--sandstone)', borderRadius: 6, boxShadow: '0 20px 48px rgba(26,26,23,0.28)', zIndex: 300, fontFamily: 'var(--font-sans)', color: 'var(--night-owl)' }}>
      <div style={{ padding: '16px 18px', borderBottom: '1px solid var(--sandstone)', background: 'var(--cream)', borderRadius: '6px 6px 0 0' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, letterSpacing: '-0.01em' }}>Tweaks</div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', fontWeight: 600, textTransform: 'uppercase', color: 'var(--sovana-gold)', marginTop: 4 }}>// Sovana · live knobs</div>
      </div>
      <div style={{ padding: 16, maxHeight: '70vh', overflow: 'auto' }}>
        <div style={{ marginBottom: 18 }}><div style={lbl}>Theme</div>{seg([['light','Cream'],['dark','Obsidian']], theme, v => apply({ theme: v }))}</div>
        <div style={{ marginBottom: 18 }}><div style={lbl}>Hero layout</div>{seg([['editorial','Editorial'],['split','Split'],['bleed','Bleed']], heroVariant, v => apply({ heroVariant: v }))}</div>
        <div style={{ marginBottom: 18 }}><div style={lbl}>Gold accent</div>{seg([['subtle','Subtle'],['medium','Medium'],['bold','Bold']], accent, v => apply({ accent: v }))}</div>
        <div style={{ marginBottom: 18 }}><div style={lbl}>Ornaments</div>{seg([[true,'On'],[false,'Off']], ornaments, v => apply({ ornaments: v }))}</div>
        <div style={{ marginBottom: 18 }}><div style={lbl}>Headline</div>
          <input style={inp} value={headline.a} onChange={e => apply({ headline: { ...headline, a: e.target.value }})} placeholder="Line A" />
          <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
            <input style={{ ...inp, flex: 2 }} value={headline.b} onChange={e => apply({ headline: { ...headline, b: e.target.value }})} placeholder="Line B start" />
            <input style={{ ...inp, flex: 1 }} value={headline.accent} onChange={e => apply({ headline: { ...headline, accent: e.target.value }})} placeholder="accent" />
          </div>
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--tuscan-earth)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>// Click the hero headline to edit inline</div>
      </div>
    </div>
  );
}

window.Modal = Modal;
window.InquiryModal = InquiryModal;
window.PropertyModal = PropertyModal;
window.TweaksPanel = TweaksPanel;
