/* global React, Icon, Eyebrow, Button, Reveal, Marquee */
const { useState } = React;

// Unsplash placeholder photography. Stable photo IDs; swap for real client work.
const PHOTOS = {
  hero:  'https://images.unsplash.com/photo-1493663284031-b7e3aefcae8e?auto=format&fit=crop&w=900&q=85',
  about: 'https://images.unsplash.com/photo-1559136555-9303baea8ebd?auto=format&fit=crop&w=900&q=85',
};

// Tweakable defaults — read from window.__rgTweaks if the host wrote any in.
const T = () => (typeof window !== 'undefined' && window.__rgTweaks) || {};

// ============================================================
// HOME
// ============================================================
function Home({ setPage, headline }) {
  // Re-render on tweak changes
  const [, setTick] = useState(0);
  React.useEffect(() => {
    const fn = () => setTick(x => x + 1);
    window.addEventListener('rg-tweaks', fn);
    return () => window.removeEventListener('rg-tweaks', fn);
  }, []);
  const h = headline || 'Your local web team in Las\u00a0Cruces.';
  // Italicize the last 2 words for the editorial accent
  const words = h.split(' ');
  const tail = words.slice(-2).join(' ');
  const head = words.slice(0, -2).join(' ');
  return (
    <>
      <section className="section hero">
        <div className="hero-grid">
          <Reveal>
            <Eyebrow>Las Cruces, New Mexico</Eyebrow>
            <h1>{head} <em>{tail}</em></h1>
            <p className="hero-lede">
              Rio Grande Websites is a local web design team in Las Cruces. We help small businesses and individuals build clean, modern, affordable websites — and we make the whole process easy, even if you've never dealt with a website before.
            </p>
            <div className="hero-actions">
              <Button variant="primary" icon="arrow-up-right" onClick={() => setPage('contact')}>Get a free quote</Button>
              <Button variant="secondary" onClick={() => setPage('services')}>See what we do</Button>
            </div>
          </Reveal>
          <Reveal>
            <div className="hero-photo">
              <img src={PHOTOS.hero} alt="A warm New Mexico landscape near Las Cruces" loading="eager" />
              <span className="stamp">Est. 2026 · Las Cruces</span>
            </div>
          </Reveal>
        </div>
        <Reveal as="div" stagger className="hero-meta container">
          <div className="stat"><div className="num">${T().setupPrice ?? 750}<em>&nbsp;up front</em></div><div className="lbl">Website design &amp; build</div></div>
          <div className="stat"><div className="num">${T().hostingPrice ?? 40}<em>/mo</em></div><div className="lbl">Optional hosting</div></div>
          <div className="stat"><div className="num">24–48<em>h</em></div><div className="lbl">Reply time</div></div>
          <div className="stat"><div className="num">3</div><div className="lbl">People on the team</div></div>
        </Reveal>
      </section>

      <Marquee items={[
        'Cafés & bakeries', 'Boutiques', 'Photographers', 'Tradespeople',
        'Realtors', 'Therapists', 'Local nonprofits', 'Restaurants',
        'Wedding venues', 'Salons',
      ]} />

      <section className="section">
        <div className="container">
          <Reveal>
            <Eyebrow>Why choose us</Eyebrow>
            <h2 style={{ fontSize: 'clamp(32px, 4.5vw, 56px)', margin: '12px 0 48px', letterSpacing: '-0.025em', fontWeight: 600, maxWidth: 720 }}>
              Not a big faceless agency — your <em style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', color: 'var(--rg-clay-500)' }}>neighbors</em>.
            </h2>
          </Reveal>
          <Reveal as="div" stagger className="services-grid">
            <div className="service-card">
              <div className="ico"><Icon name="map-pin" size={24} /></div>
              <h3>Local &amp; personal</h3>
              <p>We're from Las Cruces and genuinely care about helping our community grow online.</p>
            </div>
            <div className="service-card t">
              <div className="ico"><Icon name="heart" size={24} /></div>
              <h3>Beginner-friendly</h3>
              <p>Never had a website before? No problem. We explain everything in plain language — no tech jargon.</p>
            </div>
            <div className="service-card y">
              <div className="ico"><Icon name="sun" size={24} /></div>
              <h3>Affordable pricing</h3>
              <p>Professional websites at prices that work for small businesses and startups.</p>
            </div>
          </Reveal>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <Reveal as="div" className="cta">
            <Eyebrow>Ready when you are</Eyebrow>
            <h2>Let's build your <em>website</em>.</h2>
            <p>Tell us a little about your project. We reply within 24–48 hours.</p>
            <Button variant="primary" icon="arrow-up-right" onClick={() => setPage('contact')}>Get a free quote</Button>
          </Reveal>
        </div>
      </section>
    </>
  );
}

// ============================================================
// SERVICES & PRICING
// ============================================================
function Services({ setPage }) {
  const services = [
    'Custom website design & development',
    'Responsive / mobile-friendly websites',
    'Website hosting',
    'Landing pages for small businesses',
    'Website redesigns & updates',
    'Basic SEO setup',
    'Ongoing website maintenance',
  ];
  return (
    <section className="section" style={{ paddingTop: 160 }}>
      <div className="container">
        <Reveal>
          <Eyebrow>Services &amp; pricing</Eyebrow>
          <h1 style={{ fontSize: 'clamp(48px, 7vw, 96px)', lineHeight: 0.98, letterSpacing: '-0.03em', margin: '16px 0 24px', maxWidth: '14ch', fontWeight: 600 }}>
            Simple pricing, <em style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', color: 'var(--rg-clay-500)' }}>clear</em> work.
          </h1>
          <p style={{ fontSize: 18, color: 'var(--rg-fg-soft)', maxWidth: 560, marginBottom: 64 }}>
            Every project is a little different. Below is what most clients pick — reach out for a free quote tailored to your needs.
          </p>
        </Reveal>

        <Reveal as="div" stagger style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 64 }} className="pricing-grid">
          <div className="service-card" style={{ padding: '40px 36px' }}>
            <Eyebrow>Design &amp; development</Eyebrow>
            <h3 style={{ fontSize: 32, marginTop: 16 }}><span style={{ color: 'var(--rg-clay-500)' }}>${T().setupPrice ?? 750}<span style={{ fontSize: 18, color: 'var(--rg-fg-muted)', fontWeight: 500 }}> · one-time</span></span></h3>
            <p>A new website, designed and built for you — paid up front. We talk through what you need, sketch it, build it, and launch it.</p>
            <Button variant="secondary" icon="arrow-up-right" onClick={() => setPage('contact')}>Get a quote</Button>
          </div>
          <div className="service-card t" style={{ padding: '40px 36px' }}>
            <Eyebrow>Hosting</Eyebrow>
            <h3 style={{ fontSize: 32, marginTop: 16 }}><span style={{ color: 'var(--rg-turq-700)' }}>${T().hostingPrice ?? 40}<span style={{ fontSize: 18, color: 'var(--rg-fg-muted)', fontWeight: 500 }}> / month</span></span></h3>
            <p>Optional — if you'd like us to host it for you. Fast, reliable servers and we keep an eye on it. You get one less thing to think about.</p>
            <Button variant="secondary" onClick={() => setPage('contact')}>Learn more</Button>
          </div>
        </Reveal>

        <Reveal>
          <Eyebrow>Everything we offer</Eyebrow>
          <ul style={{ listStyle: 'none', padding: 0, margin: '24px 0 0', display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '4px 32px', maxWidth: 880 }}>
            {services.map((s, i) => (
              <li key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '18px 0', borderBottom: '1px solid var(--rg-line)', fontSize: 17, color: 'var(--rg-fg)' }}>
                <span style={{ width: 28, height: 28, borderRadius: 999, background: 'var(--rg-clay-100)', color: 'var(--rg-clay-700)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <Icon name="check" size={16} stroke={2.25} />
                </span>
                {s}
              </li>
            ))}
          </ul>
        </Reveal>
      </div>
    </section>
  );
}

// ============================================================
// ABOUT — team
// ============================================================
function About({ setPage }) {
  const team = [
    { tone: 'clay',    icon: 'palette',     role: 'Web designer',           name: 'Andres', about: 'The creative eye behind Rio Grande Websites — focused on making every site look great, feel easy to use, and match the personality of each client\'s brand.', skills: 'Layout design · Color · UI/UX · Visual assets' },
    { tone: 'turq',    icon: 'pen-tool',    role: 'Web developer',          name: 'Keith',  about: 'The technical backbone of the team — turns designs into real, working websites that load fast and look great on any device.', skills: 'HTML · CSS · JavaScript · WordPress / Wix / Squarespace' },
    { tone: 'yellow',  icon: 'sparkles',    role: 'Marketing & social',     name: 'Carlos', about: 'Makes sure Rio Grande Websites and our clients get noticed — from social media to client outreach, the strategy behind every project.', skills: 'Social · Content · SEO basics · Outreach' },
  ];
  return (
    <>
      <section className="section about-hero">
        <div className="container">
          <Reveal>
            <Eyebrow>About us</Eyebrow>
            <h1>Three of us, <em>made</em> in Las&nbsp;Cruces.</h1>
          </Reveal>
          <Reveal as="div" stagger className="about-grid">
            <div>
              <p>Rio Grande Websites is a small local team. We started because we wanted to help small businesses and individuals around Las Cruces show up online — without the markup, the jargon, or the runaround.</p>
              <p>We're beginner-friendly on purpose. If this is your first website, we'll walk you through every step in plain language. If it's your fifth, we'll skip the part you already know.</p>
              <p>Either way, you talk to a real person who lives down the road.</p>
              <Button variant="primary" icon="arrow-up-right" onClick={() => setPage('contact')}>Get in touch</Button>
            </div>
            <div
              className="about-image"
              role="img"
              aria-label="A warm portrait of the southwest"
              style={{ backgroundImage: `url(${PHOTOS.about})` }}
            />
          </Reveal>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 0 }}>
        <div className="container">
          <Reveal>
            <Eyebrow>Meet the team</Eyebrow>
            <h2 style={{ fontSize: 'clamp(32px, 4.5vw, 56px)', margin: '12px 0 48px', letterSpacing: '-0.025em', fontWeight: 600 }}>The people behind your site.</h2>
          </Reveal>
          <Reveal as="div" stagger className="team-grid">
            {team.map((p) => (
              <div className="team-card" key={p.role}>
                <div className="ph" style={{
                  background: p.tone === 'clay'   ? 'linear-gradient(160deg, #F4DDD3, #C97B63)'
                            : p.tone === 'turq'   ? 'linear-gradient(160deg, #D6F0EE, #49B8B1)'
                            :                       'linear-gradient(160deg, #FBE9C2, #F2C14E)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(43,43,43,0.55)',
                }}>
                  <Icon name={p.icon} size={56} stroke={1.4} />
                </div>
                <div className="body" style={{ padding: '24px 26px 28px' }}>
                  <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--rg-clay-700)' }}>{p.role}</div>
                  <div className="name" style={{ marginTop: 6, fontSize: 22 }}>{p.name}</div>
                  <p style={{ fontSize: 14, color: 'var(--rg-fg-soft)', lineHeight: 1.6, margin: '12px 0 16px' }}>{p.about}</p>
                  <div style={{ fontSize: 12, color: 'var(--rg-fg-muted)', paddingTop: 14, borderTop: '1px solid var(--rg-line)' }}>{p.skills}</div>
                </div>
              </div>
            ))}
          </Reveal>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <Reveal>
            <Eyebrow>Client testimonials</Eyebrow>
            <h2 style={{ fontSize: 'clamp(32px, 4.5vw, 56px)', margin: '12px 0 32px', letterSpacing: '-0.025em', fontWeight: 600 }}>Coming soon.</h2>
            <div style={{ background: 'var(--rg-bg-card)', borderRadius: 'var(--r-2xl)', padding: '40px 44px', boxShadow: 'var(--shadow-sm)', maxWidth: 720 }}>
              <p style={{ fontSize: 18, color: 'var(--rg-fg-muted)', margin: 0, fontStyle: 'italic' }}>
                "[ Client quote will go here once we collect our first reviews. ]"
              </p>
              <div style={{ marginTop: 16, fontSize: 13, color: 'var(--rg-fg-muted)' }}>— [Client name], [Business or Location]</div>
            </div>
          </Reveal>
        </div>
      </section>
    </>
  );
}

// ============================================================
// CONTACT
// ============================================================
// Web3Forms key — public on purpose; allowed-domain check happens server-side.
const WEB3FORMS_KEY = '66a41c45-43b4-4752-8c3c-4b71681126a1';

function Contact() {
  const [status, setStatus] = useState('idle'); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = useState('');
  const [form, setForm] = useState({ name: '', email: '', project: 'New website', message: '' });
  const upd = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;
    setStatus('sending');
    setErrorMsg('');
    try {
      const fd = new FormData(e.currentTarget);
      // Honeypot: if filled, it's a bot — silently no-op.
      if (fd.get('botcheck')) { setStatus('sent'); return; }
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Accept': 'application/json' },
        body: fd,
      });
      const data = await res.json();
      if (data.success) {
        setStatus('sent');
        setForm({ name: '', email: '', project: 'New website', message: '' });
      } else {
        setStatus('error');
        setErrorMsg(data.message || 'Something went wrong. Please email us directly.');
      }
    } catch (err) {
      setStatus('error');
      setErrorMsg('Network error. Please email us directly.');
    }
  };

  const btnLabel =
    status === 'sending' ? 'Sending…' :
    status === 'sent'    ? 'Sent — talk soon' :
                           'Send';
  return (
    <section className="section" style={{ paddingTop: 160 }}>
      <div className="container">
        <Reveal>
          <Eyebrow>Contact us</Eyebrow>
          <h1 style={{ fontSize: 'clamp(48px, 7vw, 96px)', lineHeight: 0.98, letterSpacing: '-0.03em', margin: '16px 0 16px', maxWidth: '14ch', fontWeight: 600 }}>
            Ready to <em style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', color: 'var(--rg-clay-500)' }}>get</em> started?
          </h1>
          <p style={{ fontSize: 18, color: 'var(--rg-fg-soft)', maxWidth: 540 }}>
            Reach out — we'd love to hear about your project. We reply within 24–48 hours.
          </p>
        </Reveal>
        <Reveal as="div" stagger className="contact-grid">
          <div className="contact-info">
            <div className="row">
              <div className="ico"><Icon name="mail" size={20} /></div>
              <div><div className="lbl">Email</div><div className="val">riograndeweb22@gmail.com</div></div>
            </div>
            <div className="row">
              <div className="ico"><Icon name="map-pin" size={20} /></div>
              <div><div className="lbl">Location</div><div className="val">Las Cruces, New Mexico</div></div>
            </div>
            <div className="row">
              <div className="ico"><Icon name="sun" size={20} /></div>
              <div><div className="lbl">Response time</div><div className="val">Within 24–48 hours</div></div>
            </div>
          </div>
          <form className="contact-form" onSubmit={submit}>
            <input type="hidden" name="access_key" value={WEB3FORMS_KEY} />
            <input type="hidden" name="subject" value="New project inquiry — Rio Grande Websites" />
            <input type="hidden" name="from_name" value={form.name || 'Website inquiry'} />
            {/* Honeypot — hidden from real users via inline style */}
            <input type="checkbox" name="botcheck" tabIndex="-1" autoComplete="off"
                   style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }} />
            <div className="contact-row">
              <div className="field"><label>Your name</label><input name="name" required value={form.name} onChange={upd('name')} placeholder="Your name" /></div>
              <div className="field"><label>Email</label><input type="email" name="email" required value={form.email} onChange={upd('email')} placeholder="you@example.com" /></div>
            </div>
            <div className="field">
              <label>What do you need?</label>
              <select name="project" value={form.project} onChange={upd('project')}>
                <option>New website</option>
                <option>Website redesign</option>
                <option>Landing page</option>
                <option>Hosting only</option>
                <option>Maintenance / updates</option>
                <option>Something else</option>
              </select>
            </div>
            <div className="field">
              <label>Tell us a little about your project</label>
              <textarea rows="5" name="message" required value={form.message} onChange={upd('message')} placeholder="A few sentences is plenty — we'll follow up with questions." />
            </div>
            <Button variant="primary" icon="arrow-up-right">{btnLabel}</Button>
            {status === 'sent' && (
              <div role="status" style={{ fontSize: 14, color: 'var(--rg-success)', marginTop: 4 }}>
                Thanks — we got your message and will be in touch within 24–48 hours.
              </div>
            )}
            {status === 'error' && (
              <div role="alert" style={{ fontSize: 14, color: 'var(--rg-error)', marginTop: 4 }}>
                {errorMsg} <a href="mailto:riograndeweb22@gmail.com">riograndeweb22@gmail.com</a>
              </div>
            )}
          </form>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { Home, Services, About, Contact });
