// Sub-pages: About, Listings, Buyer's Guide, Seller's Guide, Blog, Contact, Communities
const { useState: useStateP } = React;

// ====================================================
// About
// ====================================================
function AboutPage({ setPage }) {
  return (
    <main>
      <div className="page-header shell container">
        <div className="crumbs"><span>About</span> · Seenu George · Real Estate Advisor</div>
        <h1 className="display">A trusted partner in<br/>your <em className="display-italic">real estate journey.</em></h1>
      </div>

      <section className="section shell container">
        <div className="about-intro">
          <div className="about-portrait">
            <picture style={{display:'contents'}}>
              <source srcSet="images/seenu-portrait.webp" type="image/webp" />
              <img src="images/seenu-portrait.png" width="543" height="543" loading="lazy" decoding="async" alt="Seenu George, Real Estate Advisor"
                style={{width:'100%', height:'100%', objectFit:'cover', objectPosition:'center top', display:'block'}} />
            </picture>
          </div>
          <div className="about-body">
            <p>My interest in real estate sparked when I bought my first home several years ago, that single experience ignited a passion I couldn't ignore. With a background deeply rooted in customer service, I made the switch to become a trusted partner for fellow Albertans in their own real estate journeys.</p>
            <p>Having lived in multiple cities across Canada, I understand both the excitement and the challenges of relocating firsthand. I'm dedicated to fulfilling my clients' real estate dreams by identifying the opportunities that offer maximum value for their assets.</p>
            <p>I'm known for a strong work ethic, exceptional customer service, and unwavering dedication, a genuine advocate in every transaction. Outside of work, I cherish time spent with my husband and our three daughters.</p>
            <p>If you're considering a move, whether it's next month or next year, I'd welcome an unhurried conversation. The best moves rarely begin with a listing.</p>
          </div>
        </div>
      </section>

      <section className="shell container">
        <div className="stats-strip">
          {STATS.map((s, i) => (
            <div key={i} className="stat">
              <div className="num display">{s.num}</div>
              <div className="lbl">{s.lbl}</div>
            </div>
          ))}
        </div>
      </section>

      <section className="section shell container">
        <div className="section-header">
          <div>
            <span className="eyebrow">,  What I bring</span>
            <h2 className="display" style={{marginTop: 18}}>The <em className="display-italic">difference.</em></h2>
          </div>
          <div className="meta">
            <p>A short, honest summary of what shapes how I work, happy to expand on any of it in person.</p>
          </div>
        </div>
        <div className="creds-grid">
          {[
            { year: '01', title: 'Customer-Service Roots', sub: 'A career built on service long before real estate, it still shapes every client relationship.' },
            { year: '02', title: 'Lived Coast to Coast', sub: 'Homes in multiple Canadian cities. I know relocation from the inside.' },
            { year: '03', title: 'Maximum-Value Focus', sub: 'I identify the opportunities that get the most value from your assets.' },
            { year: '04', title: 'Family-Grounded', sub: 'A mom of three daughters, I understand what families need from a home.' },
            { year: '05', title: 'Backed by eXp Realty', sub: 'The support and reach of one of North America\'s largest brokerages.' },
            { year: '06', title: 'Licensed in Alberta', sub: 'A RECA-licensed real estate professional, serving Calgary & area.' },
          ].map((c, i) => (
            <div key={i} className="cred">
              <div className="year">{c.year}</div>
              <div className="title">{c.title}</div>
              <div className="sub">{c.sub}</div>
            </div>
          ))}
        </div>
      </section>

      <section className="section shell container">
        <Testimonial />
      </section>

      <section className="section shell container" style={{paddingTop: 0, textAlign:'center'}}>
        <h2 className="display" style={{fontSize:'clamp(48px,6vw,88px)', maxWidth: '14ch', margin: '0 auto 32px'}}>
          The next move<br/>begins with <em className="display-italic">a conversation.</em>
        </h2>
        <button className="btn btn-gold" onClick={() => setPage('contact')}>
          Schedule a private consultation
          <span className="arrow">→</span>
        </button>
      </section>
    </main>
  );
}

// Pull Testimonial from home.jsx scope by recreating a slim version
function Testimonial() {
  const r = (window.REVIEWS && window.REVIEWS[1]) || null;
  if (!r) return null;
  return (
    <div className="testimonial">
      <div className="testimonial-portrait">
        <picture style={{display:'contents'}}>
          <source srcSet="images/seenu-portrait.webp" type="image/webp" />
          <img src="images/seenu-portrait.png" width="543" height="543" loading="lazy" decoding="async" alt="Seenu George"
            style={{width:'100%', height:'100%', objectFit:'cover', objectPosition:'center top', display:'block'}} />
        </picture>
      </div>
      <div>
        <span className="eyebrow">,  What clients say</span>
        <div className="testimonial-quote" style={{marginTop: 24}}>
          {r.quote}
        </div>
        <div className="testimonial-attrib">
          <div className="who">
            {r.name}
            <small>★★★★★ · Verified client review</small>
          </div>
        </div>
      </div>
    </div>
  );
}

// ====================================================
// Listings (search results)
// ====================================================
function ListingsPage({ setPage }) {
  const [place, setPlace] = useStateP('Calgary');
  const [minP, setMinP] = useStateP('0');
  const [maxP, setMaxP] = useStateP('0');
  const [beds, setBeds] = useStateP('Any');

  // Tiered price steps, same as the homepage search.
  const priceSteps = React.useMemo(() => {
    const a = [];
    for (let v = 100000; v < 1000000; v += 100000) a.push(v);
    for (let v = 1000000; v < 2000000; v += 250000) a.push(v);
    for (let v = 2000000; v <= 10000000; v += 500000) a.push(v);
    return a;
  }, []);
  const fmtP = (v) => v >= 1000000
    ? '$' + (v / 1000000).toFixed(v % 1000000 === 0 ? 0 : (v % 500000 === 0 ? 1 : 2)).replace(/\.0$/, '') + 'M'
    : '$' + (v / 1000) + 'k';

  const runSearch = () => {
    const min = parseInt(minP) || 0;
    const max = parseInt(maxP) || 0;
    window.openIdxSearch({
      place,
      beds: beds !== 'Any' ? parseInt(beds) : 0,
      minPrice: min,
      maxPrice: max > 0 ? max : 100000000,
    });
  };

  const collections = [
    { label: 'All MLS® Listings', link: 'allListings' },
    { label: 'Just Listed', link: 'justListed' },
    { label: 'Just Reduced', link: 'justReduced' },
    { label: "Seenu's Listings", link: 'ourListings' },
  ];

  return (
    <main>
      <div className="page-header shell container">
        <div className="crumbs">Home · <span>Listings</span></div>
        <h1 className="display">Search the live<br/>Calgary &amp; area <em className="display-italic">MLS®.</em></h1>
      </div>

      <section className="section shell container">
        {/* Real search → BoldTrail */}
        <div className="search-panel">
          <div className="sp-field">
            <label>Area</label>
            <select value={place} onChange={(e)=>setPlace(e.target.value)}>
              {(window.idxPlaces ? window.idxPlaces() : ['Calgary']).map(p => (
                <option key={p} value={p}>{p}</option>
              ))}
            </select>
          </div>
          <div className="sp-field">
            <label>Min price</label>
            <select value={minP} onChange={(e)=>setMinP(e.target.value)}>
              <option value="0">No min</option>
              {priceSteps.map(v => <option key={v} value={v}>{fmtP(v)}</option>)}
            </select>
          </div>
          <div className="sp-field">
            <label>Max price</label>
            <select value={maxP} onChange={(e)=>setMaxP(e.target.value)}>
              <option value="0">No max</option>
              {priceSteps.map(v => <option key={v} value={v}>{fmtP(v)}</option>)}
            </select>
          </div>
          <div className="sp-field">
            <label>Bedrooms</label>
            <select value={beds} onChange={(e)=>setBeds(e.target.value)}>
              <option>Any</option><option>2+</option><option>3+</option><option>4+</option><option>5+</option><option>6+</option>
            </select>
          </div>
          <div className="sp-field">
            <label>Property type</label>
            <select>
              <option>Any type</option>
              <option>Detached</option>
              <option>Condo / Apartment</option>
              <option>Townhouse</option>
              <option>Acreage</option>
              <option>Land</option>
              <option>New build</option>
            </select>
          </div>
          <button className="sp-submit" onClick={runSearch}>
            Search MLS®<span className="arrow">→</span>
          </button>
        </div>

        <div style={{marginTop: 16}}>
          <a className="link-arrow" onClick={() => window.openIdxLink('advanced')}>
            Open the full advanced search (all filters) →
          </a>
        </div>

        {/* BoldTrail widget slot, real listings render here when embed is pasted */}
        <div id="boldtrail-listings-widget" style={{marginTop: 56}}></div>

        {/* Quick collections */}
        <div style={{marginTop: 56}}>
          <span className="eyebrow" style={{display:'block', marginBottom: 24}}>,  Browse by collection</span>
          <div className="listings-hub-row">
            {collections.map(c => (
              <button key={c.link} className="listings-hub-card" onClick={() => window.openIdxLink(c.link)}>
                <span className="lhc-label">{c.label}</span>
                <span className="lhc-go">Open →</span>
              </button>
            ))}
          </div>
        </div>

        {/* Browse by area */}
        <div style={{marginTop: 56}}>
          <span className="eyebrow" style={{display:'block', marginBottom: 24}}>,  Browse by area</span>
          <div style={{display:'flex', flexWrap:'wrap', gap: 12}}>
            {(window.idxPlaces ? window.idxPlaces() : []).map(p => (
              <button key={p} className="btn btn-ghost btn-sm" onClick={() => window.openIdxSearch({ place: p })}>
                {p}<span className="arrow">→</span>
              </button>
            ))}
          </div>
        </div>

        {/* CREB®/MLS® compliance, required */}
        <p style={{marginTop: 64, paddingTop: 28, borderTop:'1px solid var(--hairline)',
          fontFamily:'var(--mono)', fontSize: 11, lineHeight: 1.7, letterSpacing:'0.03em',
          color:'var(--muted)', maxWidth:'80ch'}}>
          {(window.IDX && window.IDX.COMPLIANCE) || ''}
        </p>
      </section>
    </main>
  );
}

// ====================================================
// Communities / Areas served
// ====================================================
function CommunitiesPage({ setPage }) {
  return (
    <main>
      <div className="page-header shell container">
        <div className="crumbs">Home · <span>Areas Served</span></div>
        <h1 className="display">Calgary &amp; the<br/><em className="display-italic">communities around it.</em></h1>
      </div>

      <section className="section shell container">
        <div style={{maxWidth:'62ch', marginBottom: 72}}>
          <p className="lede">
            I help buyers and sellers across Calgary and the surrounding cities and towns, from the urban core to the foothills and the Bow Valley. Choose an area below to browse every active MLS® listing there, updated in real time.
          </p>
        </div>

        <div style={{display:'flex', flexDirection:'column'}}>
          {AREAS.map((a, i) => (
            <button key={a.place}
              onClick={() => window.openIdxSearch({ place: a.place })}
              style={{display:'grid', gridTemplateColumns:'80px 1fr auto', gap: 40, alignItems:'center',
                textAlign:'left', padding:'40px 0', borderBottom:'1px solid var(--hairline)',
                cursor:'pointer', background:'none'}}
              className="area-row">
              <span className="neigh-num">{a.num}</span>
              <div>
                <h3 className="display area-row-name" style={{fontSize: 'clamp(36px,4vw,56px)', fontWeight:300, margin:'0 0 14px', lineHeight:1}}>{a.name}</h3>
                <p className="body" style={{margin:0, maxWidth:'56ch'}}>{a.blurb}</p>
              </div>
              <span className="link-arrow" style={{whiteSpace:'nowrap'}}>View listings →</span>
            </button>
          ))}
        </div>

        <div style={{marginTop: 64, display:'flex', flexWrap:'wrap', gap:12}}>
          <button className="btn btn-gold btn-sm" onClick={() => window.openIdxLink('allListings')}>All MLS® Listings <span className="arrow">→</span></button>
          <button className="btn btn-ghost btn-sm" onClick={() => window.openIdxLink('advanced')}>Advanced search (all filters) <span className="arrow">→</span></button>
        </div>
      </section>
    </main>
  );
}

// ====================================================
// Buyer's & Seller's Guides
// ====================================================
function GuidePage({ kind, setPage }) {
  const data = kind === 'buyer' ? {
    title: 'Buying',
    sub: 'How a private purchase comes together.',
    crumb: "Buyer's Guide",
    intro: "Buying at the top of Calgary's market is rarely a transaction. It's a slow assembly of trust, timing, financing and quiet introductions to homes that never reach MLS. Here's how I work, end to end.",
    steps: [
      { n: '01', t: 'The first conversation.', p: 'A 60-minute coffee, usually at Rosso, Phil & Sebastian, or your kitchen table. We talk about why you\'re moving, when, and what "right" looks like. No pressure to commit.' },
      { n: '02', t: 'A private buyer\'s brief.', p: 'I prepare a tailored brief: communities, comparables, school catchments, build quality, walkability. This becomes our north star, and it evolves as we tour.' },
      { n: '03', t: 'Financing, quietly.', p: 'I introduce you to one of three private-banking mortgage advisors I trust. Pre-approval letters are often the difference between an accepted offer and a missed one.' },
      { n: '04', t: 'Touring, including the off-market.', p: 'Most homes I show you above $3M are not on MLS. We tour evenings and weekends, with photos and floorplans sent ahead so we never waste a Saturday.' },
      { n: '05', t: 'The offer.', p: 'I write conservative, well-structured offers. Inspections, financing conditions, deposit timing, every clause is negotiated with the seller\'s motivation in mind.' },
      { n: '06', t: 'Conditions, then close.', p: 'Inspector, surveyor, lawyer, I coordinate the entire condition period. Most closings happen 30 to 60 days from accepted offer, with weekly status notes from me.' },
      { n: '07', t: 'After possession.', p: 'I keep a list of trades, millwork, landscape, AV, I\'d send my own family to. Six months in, we have coffee again. Two years in, you call me about the next house.' },
    ],
  } : {
    title: 'Selling',
    sub: 'How a discreet sale is staged, marketed and closed.',
    crumb: "Seller's Guide",
    intro: "A well-sold luxury home looks effortless from the outside. Underneath: 90 days of preparation, a private buyer list cultivated over a decade, and a marketing approach that respects your privacy while creating real urgency. Here's the method.",
    steps: [
      { n: '01', t: 'The valuation, honestly.', p: 'I walk your home and prepare a written valuation grounded in true comparables, not the optimistic number a less experienced agent will quote to win the listing.' },
      { n: '02', t: 'Preparing the home.', p: 'I\'ll recommend (and project-manage) the small list of changes that move price: paint, lighting, landscape, photography-grade decluttering. Usually 3 to 6 weeks.' },
      { n: '03', t: 'Photography and film.', p: 'Architectural-grade stills, twilight exteriors, and a short film. Shot by photographers I\'ve worked with for 10+ years. No drone footage of your neighbour\'s yard.' },
      { n: '04', t: 'The private list, first.', p: 'For 2 to 3 weeks, your home is shown only to a curated list of qualified buyers and the dozen agents in Calgary who represent them. Many homes sell here.' },
      { n: '05', t: 'Public launch.', p: 'If we go to MLS, we go beautifully, full presentation, printed brochure, dedicated microsite, geo-targeted ads. Open houses are by appointment only.' },
      { n: '06', t: 'Negotiation.', p: 'Most offers come with conditions. I push back on the soft ones, accept the reasonable ones, and tell you the truth about every term. Your interests, always, first.' },
      { n: '07', t: 'Closing and beyond.', p: 'Lawyer, inspector, possession-day logistics, I run the full timeline. After closing, I send a card. A year later, I check in. That\'s the practice.' },
    ],
  };

  return (
    <main>
      <div className="page-header shell container">
        <div className="crumbs">Home · <span>{data.crumb}</span></div>
        <h1 className="display">{data.title}.<br/><em className="display-italic">{data.sub}</em></h1>
      </div>

      <section className="section shell container">
        <div className="guide-intro">
          <div className="guide-toc">
            <span className="eyebrow" style={{marginBottom: 16, display:'block'}}>,  Contents</span>
            {data.steps.map(s => (
              <a key={s.n}>
                <span className="num">{s.n}</span>
                <span className="ttl">{s.t.replace('.', '')}</span>
              </a>
            ))}
          </div>
          <div>
            <p className="lede" style={{maxWidth: '48ch', marginBottom: 64}}>{data.intro}</p>

            {data.steps.map(s => (
              <div key={s.n} className="guide-step">
                <div className="num display">{s.n}</div>
                <div>
                  <h3>{s.t}</h3>
                  <p>{s.p}</p>
                </div>
              </div>
            ))}

            <div style={{marginTop: 64, padding: 48, border: '1px solid var(--hairline-strong)', background:'var(--ink-soft)'}}>
              <span className="eyebrow">,  Ready?</span>
              <h3 className="display" style={{fontSize: 40, fontWeight: 300, margin: '20px 0 24px', maxWidth:'18ch', lineHeight: 1.1}}>
                The first step is a conversation, never a commitment.
              </h3>
              <button className="btn btn-gold" onClick={() => setPage('contact')}>
                Book a {kind === 'buyer' ? 'buyer' : 'seller'} consultation
                <span className="arrow">→</span>
              </button>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

// ====================================================
// Blog / Journal
// ====================================================
function BlogPage({ setPage }) {
  const sources = [
    {
      cat: 'CREB®',
      title: 'Calgary Monthly Housing Statistics',
      desc: 'The Calgary Real Estate Board publishes official monthly data on prices, sales, inventory and benchmark values across the city and its districts.',
      url: 'https://www.creb.com/Housing_Statistics/',
      action: 'View CREB® stats',
    },
    {
      cat: 'CREB®',
      title: 'Calgary Yearly & Regional Outlook',
      desc: 'CREB®’s annual forecast and regional reports for Calgary, Airdrie, Cochrane, Chestermere, Okotoks and surrounding areas.',
      url: 'https://www.creb.com/Housing_Statistics/Yearly/',
      action: 'View outlook',
    },
    {
      cat: 'CREA®',
      title: 'National & Provincial Statistics',
      desc: 'The Canadian Real Estate Association’s national MLS® Home Price Index and provincial trends, useful context for Alberta buyers and sellers.',
      url: 'https://www.crea.ca/housing-market-stats/',
      action: 'View CREA® stats',
    },
    {
      cat: 'Alberta',
      title: 'Alberta Real Estate Association',
      desc: 'Province-wide housing market insight and consumer resources from AREA.',
      url: 'https://www.areahub.ca/',
      action: 'Visit AREA',
    },
  ];

  return (
    <main>
      <div className="page-header shell container">
        <div className="crumbs">Home · <span>Market Insights</span></div>
        <h1 className="display">The Calgary<br/>market, <em className="display-italic">in real numbers.</em></h1>
      </div>

      <section className="section shell container">
        <div className="section-header">
          <div>
            <span className="eyebrow">,  Official Sources</span>
            <h2 className="display" style={{marginTop: 18}}>Where I get<br/><em className="display-italic">my data.</em></h2>
          </div>
          <div className="meta">
            <p>Rather than recycle second-hand commentary, I point you to the official, up-to-date statistics I use with my own clients. For what they mean for <em>your</em> home or search, let's talk.</p>
            <a className="link-arrow" onClick={() => setPage('contact')}>Ask me about your market →</a>
          </div>
        </div>

        <div className="insights-grid">
          {sources.map((s, i) => (
            <a key={i} className="insight-card" href={s.url} target="_blank" rel="noopener">
              <div className="meta">
                <span className="cat">{s.cat}</span>
                <span className="date">Official source ↗</span>
              </div>
              <h3 className="display">{s.title}</h3>
              <p>{s.desc}</p>
              <div className="insight-go">{s.action} →</div>
            </a>
          ))}
        </div>

        <div className="cta-split" style={{marginTop: 80, padding: 64, background:'var(--ink-soft)', border:'1px solid var(--hairline)'}}>
          <div>
            <span className="eyebrow">,  Seenu's Notes</span>
            <h3 className="display" style={{fontSize: 44, fontWeight: 300, margin: '16px 0 16px', maxWidth: '18ch', lineHeight: 1.1}}>
              Personal market notes, <em className="display-italic">coming soon.</em>
            </h3>
            <p className="body" style={{marginBottom: 0}}>I'm starting to share short, honest takes on what I'm seeing across Calgary and area, neighbourhood by neighbourhood. Want them when they go live? Create a free account and I'll keep you posted.</p>
          </div>
          <div style={{display:'flex', flexDirection:'column', gap: 14, justifyContent:'center'}}>
            <button className="btn btn-gold" onClick={() => window.openIdxRegister()} style={{justifyContent:'space-between'}}>
              Get market updates <span className="arrow">→</span>
            </button>
            <button className="btn btn-ghost" onClick={() => setPage('contact')} style={{justifyContent:'space-between'}}>
              Ask Seenu a question <span className="arrow">→</span>
            </button>
          </div>
        </div>
      </section>
    </main>
  );
}

// ====================================================
// Contact
// ====================================================
function ContactPage() {
  const [submitted, setSubmitted] = useStateP(false);
  const [sending, setSending] = useStateP(false);
  const [consent, setConsent] = useStateP(false);
  const [error, setError] = useStateP('');
  // If the visitor arrived via the calculator's "mortgage broker" button,
  // preselect financing intent and show a tailored heading.
  const intent = (typeof window !== 'undefined' && window.__sgContactIntent) || '';
  const isFinancing = intent === 'financing';

  // Email the lead to BOTH inboxes via FormSubmit, formatted EXACTLY as the
  // BoldTrail (kvCORE) dropbox parser expects: subject "Add Contact" with ordered
  // First Name / Last Name / Email / Phone / Source / Referrer / Hashtag / Note
  // lines. Auto-forward one inbox to the kvCORE dropbox to create the contact.
  // Each address must be activated once (FormSubmit sends a one-time link).
  // Lead notification inbox (Seenu's heads-up).
  const LEAD_EMAILS = ['seenu@homesbyseenu.ca'];
  const stamp = () => {
    const d = new Date(), p = (n) => (n < 10 ? '0' : '') + n;
    return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' +
           p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds());
  };
  const submitLead = (lead) => {
    const noteLine = '[Lead Details]: ' + (lead.note || '') +
                     (lead.note ? ' | ' : '') + 'Captured at ' + stamp();
    // Google Form → clean BoldTrail-parseable lead record (fire-and-forget).
    try {
      const fd = new FormData();
      fd.append('entry.1956110703', ((lead.first || '') + ' ' + (lead.last || '')).trim());
      fd.append('entry.1104942754', lead.email || '');
      fd.append('entry.1060949559', lead.phone || '');
      fd.append('entry.1214057666', lead.category || '');
      fd.append('entry.1126205919', noteLine);
      fetch('https://docs.google.com/forms/d/e/1FAIpQLSfT26xRUVgInNZmztj_JGd1ELK1FydjQO5ijOGhi03KWGuhjA/formResponse',
        { method: 'POST', mode: 'no-cors', body: fd }).catch(() => {});
    } catch (e) {}
    const body = {
      _subject: 'Add Contact',
      _template: 'box',
      _captcha: 'false',
      'First Name': lead.first || '',
      'Last Name': lead.last || '',
      'Email': lead.email || '',
      'Phone': lead.phone || '',
      'Source': 'Organic Website',
      'Referrer': 'homesbyseenu.ca',
      'Hashtag': lead.category || '',
      'Note': noteLine
    };
    LEAD_EMAILS.forEach((to) => {
      try {
        fetch('https://formsubmit.co/ajax/' + encodeURIComponent(to), {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
          body: JSON.stringify(body)
        }).catch(() => {});
      } catch (e) {}
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    if (!consent) { setError('Please check the consent box so Seenu can reply to you.'); return; }
    const form = e.target;
    const data = Object.fromEntries(new FormData(form).entries());
    const name = (data.name || '').trim();
    if (!name || !data.email) { setError('Please enter your name and email.'); return; }

    // Custom context → Note field (pins under "Note:" in the BoldTrail timeline)
    const noteParts = [];
    if (data.considering === 'financing') noteParts.push('MORTGAGE / FINANCING LEAD');
    if (data.considering) noteParts.push('Considering: ' + data.considering);
    if (data.message) noteParts.push('Message: ' + String(data.message).slice(0, 400));
    const note = noteParts.join(' | ');

    setSending(true);
    submitLead({
      first: name,
      last: '',
      email: data.email || '',
      phone: data.phone || '',
      category: '#contact',
      note: note
    });
    // Conversions fire ONLY for genuine ad-driven visitors (gclid / msclkid),
    // captured on landing by idx-config.jsx. Organic/direct never mis-attributes.
    if (window.uetq && window.__sgHasClickId && window.__sgHasClickId('msclkid')) {
      window.uetq.push('event', 'contact', { 'event_category': 'Lead', 'event_label': 'Contact form' });
    }
    try {
      if (window.gtag && window.__sgHasClickId && window.__sgHasClickId('gclid')) {
        window.gtag('event', 'conversion', { send_to: 'AW-18217550252/tCIiCMjri78cEKyD5-5D' });
      }
    } catch (e) {}
    setTimeout(() => { setSending(false); setSubmitted(true); }, 500);
  };

  return (
    <main>
      <div className="page-header shell container">
        <div className="crumbs">Home · <span>Contact</span></div>
        <h1 className="display">Let's find <em className="display-italic">your next home.</em></h1>
      </div>

      <section className="section shell container">
        <div className="contact-grid">
          <div>
            <p className="lede" style={{maxWidth:'42ch', marginBottom: 48}}>
              {isFinancing
                ? "Tell me a little about your plans and I'll connect you with a trusted local mortgage broker, and step in as your REALTOR® if you don't have one yet."
                : "The best moves start with a conversation. Tell me a little about what you're considering, I'll reply personally within one business day."}
            </p>

            <div className="contact-info">
              <div className="contact-block">
                <div className="lbl">Office</div>
                <div className="val">eXp Realty, Calgary<br/>#700, 1816 Crowchild Trail NW<br/>Calgary, AB T2M 3Y7</div>
              </div>
              <div className="contact-block">
                <div className="lbl">Direct</div>
                <div className="val"><a href="tel:+14038282359">+1 (403) 828-2359</a></div>
              </div>
              <div className="contact-block">
                <div className="lbl">Email</div>
                <div className="val"><a href="mailto:seenu@homesbyseenu.ca">seenu@homesbyseenu.ca</a></div>
              </div>
              <div className="contact-block">
                <div className="lbl">Hours</div>
                <div className="val" style={{fontSize: 20, lineHeight: 1.6}}>
                  Mon, Fri · 8:30, 18:00<br/>
                  Sat · By appointment<br/>
                  Sun · Family
                </div>
              </div>
            </div>
          </div>

          <div>
            {submitted ? (
              <div style={{padding: 64, border: '1px solid var(--gold)', textAlign:'center'}}>
                <div className="display" style={{fontSize: 56, color:'var(--gold)', marginBottom: 24}}>Thank you.</div>
                <p className="lede">I've received your note. You'll hear back from me personally within one business day, usually sooner.</p>
              </div>
            ) : (
              <form className="contact-form" onSubmit={handleSubmit}>
                <div className="contact-field">
                  <label>Name</label>
                  <input name="name" required />
                </div>
                <div className="contact-row">
                  <div className="contact-field">
                    <label>Email</label>
                    <input name="email" type="email" required />
                  </div>
                  <div className="contact-field">
                    <label>Phone (optional)</label>
                    <input name="phone" />
                  </div>
                </div>
                <div className="contact-field">
                  <label>I'm considering</label>
                  <select name="considering" defaultValue={isFinancing ? 'financing' : 'buying'}>
                    <option value="buying">Buying, within 3 to 12 months</option>
                    <option value="selling">Selling, preparing my home</option>
                    <option value="both">Both, moving up or downsizing</option>
                    <option value="financing">Financing, connect me with a mortgage broker</option>
                    <option value="exploring">Just exploring the market</option>
                  </select>
                </div>
                <div className="contact-field">
                  <label>Tell me a little more (optional)</label>
                  <textarea name="message" placeholder="Where you live now, where you'd like to be, ideal timing…"></textarea>
                </div>

                <label className="consent">
                  <input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)} />
                  <span>I agree to be contacted by Seenu George about my enquiry and consent to the use of my information as described in the <a onClick={(e)=>{e.preventDefault(); window.location.hash='#/privacy';}} href="#/privacy">Privacy Policy</a>. I can unsubscribe at any time.</span>
                </label>

                {error && <div className="form-error">{error}</div>}

                <button type="submit" className="btn btn-gold" style={{alignSelf:'start', marginTop: 4}} disabled={sending}>
                  {sending ? 'Sending…' : "Send, I'll reply personally"}
                  <span className="arrow">→</span>
                </button>
                <div className="kicker" style={{marginTop: 4}}>Your information is private and never sold. See our Privacy Policy.</div>
              </form>
            )}
          </div>
        </div>
      </section>
    </main>
  );
}

window.AboutPage = AboutPage;
window.ListingsPage = ListingsPage;
window.CommunitiesPage = CommunitiesPage;
window.GuidePage = GuidePage;
window.BlogPage = BlogPage;
window.ContactPage = ContactPage;
