/* global React */
// The Gamekeeper's Cottage — Home (conversion landing)
const { useState, useEffect } = React;
const NS_HOME = window.GamekeepersCottageDesignSystem_070bc7;
const { Button, Badge, Rating, Eyebrow, Card, Amenity } = NS_HOME;
const Photo = window.GKPhoto;
const useShell = window.GKuseShell;
const useReviews = window.GKuseReviews;
const reviewMonth = window.GKreviewMonth;
const reviewStats = window.GKreviewStats;
const IMG = window.GK_IMG;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "hero": "panel",
  "accent": "#2f5d3a",
  "cta": "Check rates & reserve",
  "showOffer": true
}/*EDITMODE-END*/;

const ACCENTS = { "#2f5d3a": "#356a43", "#3f6b32": "#4a7d3b", "#4a6b57": "#577e66" };

function applyAccent(hex) {
  const hover = ACCENTS[hex] || hex;
  const root = document.documentElement.style;
  root.setProperty('--color-primary', hex);
  root.setProperty('--color-primary-hover', hover);
}

function TrustStrip() {
  const stats = reviewStats(useReviews());
  const items = [
    ['star', stats.count > 0 ? stats.averageText + ' from ' + stats.count + ' guest reviews' : 'Loved by our guests'],
    ['trees', 'Set in a 100-acre wood'],
    ['bed-double', 'Sleeps 5 · 3 bedrooms'],
    ['heart-handshake', 'Owner-run, book direct'],
  ];
  return (
    <div style={{ borderBottom: '1px solid var(--border-soft)', background: 'var(--surface-card)' }}>
      <div className="container" style={{ display: 'flex', flexWrap: 'wrap', gap: '14px 40px', justifyContent: 'center', padding: '20px 32px' }}>
        {items.map(([ic, label]) => (
          <span key={label} style={{ display: 'inline-flex', alignItems: 'center', gap: 10, fontSize: 15, color: 'var(--text-body)', fontWeight: 500 }}>
            <i data-lucide={ic} style={{ width: 18, height: 18, color: 'var(--color-primary)' }}></i>{label}
          </span>
        ))}
      </div>
    </div>
  );
}

function BookingBar({ cta, overlap = true }) {
  const { openBooking } = useShell();
  const [bar, setBar] = useState({ arrive: '2026-07-18', depart: '2026-07-25', guests: '4' });
  const set = (k) => (e) => setBar((b) => ({ ...b, [k]: e.target.value }));
  // Moving arrival drags an earlier/empty departure with it.
  const onArrive = (e) => { const v = e.target.value; setBar((b) => { const next = { ...b, arrive: v }; if (v && (!b.depart || b.depart < v)) next.depart = v; return next; }); };
  return (
    <div className="container" style={{ marginTop: overlap ? -46 : 36, position: 'relative', zIndex: 5 }}>
      <div className="bookingbar">
        <label className="gk-field"><span className="gk-field__label">Arrival</span><input className="gk-input" type="date" value={bar.arrive} onChange={onArrive} /></label>
        <label className="gk-field"><span className="gk-field__label">Departure</span><input className="gk-input" type="date" value={bar.depart} onChange={set('depart')} /></label>
        <label className="gk-field"><span className="gk-field__label">Guests</span><input className="gk-input" type="number" min="1" max="5" value={bar.guests} onChange={set('guests')} /></label>
        <div className="bookingbar__cta"><Button variant="primary" size="lg" fullWidth onClick={() => openBooking(bar)} style={{ height: 50 }}>{cta}</Button></div>
      </div>
    </div>
  );
}

function Hero({ t }) {
  const { openBooking } = useShell();
  const eyebrow = 'Self-catering · near Southwold, Suffolk';
  const title = "Escape to The Gamekeeper's Cottage";
  const lead = 'A cosy cottage hidden in a hundred-acre Suffolk wood — for slow weekends, woodland walks, birdsong and proper countryside quiet.';

  if (t.hero === 'split') {
    return (
      <section className="hero">
        <div className="container gk-stack" style={{ display: 'grid', gridTemplateColumns: '1fr 1.05fr', gap: 56, alignItems: 'center', padding: '72px 32px 0' }}>
          <div>
            <Eyebrow>{eyebrow}</Eyebrow>
            <h1 className="h-display" style={{ margin: '16px 0 18px' }}>{title}</h1>
            <p className="lead" style={{ maxWidth: 460, marginBottom: 28 }}>{lead}</p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <Button variant="primary" size="lg" onClick={openBooking}>{t.cta}</Button>
              <Button variant="secondary" size="lg" as="a" href="cottage">View the cottage</Button>
            </div>
          </div>
          <Photo src={IMG.heroExterior} alt="The Gamekeeper's Cottage" ratio="5 / 4" radius="var(--radius-xl)" position="center 60%" />
        </div>
        <BookingBar cta={t.cta} overlap={false} />
      </section>
    );
  }

  const aligned = t.hero === 'panel';
  return (
    <section className="hero">
      <div className="hero__media" style={{ height: 600 }}>
        <Photo src={IMG.heroExterior} alt="The Gamekeeper's Cottage in its woodland setting" ratio="auto" position="center 58%" style={{ height: '100%', aspectRatio: 'auto', borderRadius: 0 }} />
        <div className="hero__scrim" style={{ background: aligned
          ? 'linear-gradient(90deg, rgba(18,28,16,0.86) 0%, rgba(18,28,16,0.58) 44%, rgba(18,28,16,0.20) 100%)'
          : 'linear-gradient(180deg, rgba(20,30,18,0.34) 0%, rgba(20,30,18,0.14) 38%, rgba(20,30,18,0.70) 100%)' }}></div>
        <div className="hero__inner container" style={{ alignItems: aligned ? 'flex-start' : 'center', textAlign: aligned ? 'left' : 'center' }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.92)' }}>{eyebrow}</span>
          <h1 className="h-display" style={{ color: '#fff', margin: '14px 0 0', maxWidth: aligned ? 620 : 880, textShadow: '0 2px 28px rgba(0,0,0,0.35)' }}>{title}</h1>
          <p className="lead" style={{ color: 'rgba(255,255,255,0.95)', margin: '18px 0 0', maxWidth: 560 }}>{lead}</p>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 28, justifyContent: aligned ? 'flex-start' : 'center' }}>
            <Button variant="primary" size="lg" onClick={openBooking}>{t.cta}</Button>
            <Button variant="on-dark" size="lg" as="a" href="cottage">View the cottage</Button>
          </div>
        </div>
      </div>
      <BookingBar cta={t.cta} />
    </section>
  );
}

function Story() {
  return (
    <section className="section">
      <div className="container gk-stack" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56, alignItems: 'center' }}>
        <div>
          <Eyebrow>The Cottage</Eyebrow>
          <h2 className="h2" style={{ margin: '14px 0 16px' }}>A beautiful spot for a gorgeous stay</h2>
          <p style={{ lineHeight: 1.75, margin: '0 0 14px' }}>The original Gamekeeper's Cottage sits in the middle of a hundred-acre wood, in a wonderfully secluded position — with four acres of private woodland attached for you to roam. It's your own birdwatching venue: deer, pheasants, owls, nuthatches and woodpeckers all visit the feeders.</p>
          <p style={{ lineHeight: 1.75, margin: '0 0 24px' }}>Inside it's warm and homely — a well-equipped kitchen, a cosy sitting room with a log burner and a separate dining room. It was Nick's family home as a teenager, and we keep it more like a home to share with you than a faceless rental.</p>
          <div className="tag-row" style={{ marginBottom: 26 }}>
            <Badge tone="moss">Sleeps 5</Badge><Badge tone="sage">3 bedrooms</Badge><Badge tone="gold">Log burner</Badge><Badge tone="outline">4 acres of private wood</Badge>
          </div>
          <Button variant="secondary" size="md" as="a" href="cottage">View cottage details</Button>
        </div>
        <div className="gk-photos" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gridTemplateRows: '168px 168px', gap: 12 }}>
          <div style={{ gridRow: 'span 2' }}><Photo src={IMG.living1} label="Sitting room" ratio="auto" radius={14} style={{ height: '100%', aspectRatio: 'auto' }} /></div>
          <Photo src={IMG.garden} label="The garden" ratio="auto" radius={14} style={{ height: '100%', aspectRatio: 'auto' }} />
          <Photo src={IMG.deer} label="Wildlife" ratio="auto" radius={14} style={{ height: '100%', aspectRatio: 'auto' }} />
        </div>
      </div>
    </section>
  );
}

function WhyStay() {
  const items = [
    ['trees', 'Four acres of private wood', 'Yours to roam — no footpaths, no neighbours, just woodland'],
    ['bird', 'Birdwatching from the door', 'Feeders by the windows; deer, owls and woodpeckers visit'],
    ['flame', 'Log burner & cosy interiors', 'A proper countryside sitting room for slow evenings'],
    ['moon', 'Dark, star-filled skies', 'No light pollution — the Milky Way on clear nights'],
    ['car-front', 'Easy to reach, free parking', 'Near Southwold, Minsmere, Beccles & Aldeburgh'],
    ['heart-handshake', 'Book direct with Nick', 'No agency fees — better rates and a personal welcome'],
  ];
  return (
    <section className="section section--soft">
      <div className="container">
        <div style={{ textAlign: 'center', maxWidth: 640, margin: '0 auto 48px' }}>
          <div style={{ display: 'flex', justifyContent: 'center' }}><Eyebrow>Why guests return</Eyebrow></div>
          <h2 className="h2" style={{ margin: '14px 0 0' }}>A genuine escape, not a marketplace listing</h2>
        </div>
        <div className="grid grid-3">
          {items.map(([ic, label, detail]) => (
            <Card key={label} padding="md">
              <span style={{ width: 46, height: 46, borderRadius: 999, background: 'var(--accent-fern)', color: 'var(--color-primary)', display: 'grid', placeItems: 'center', marginBottom: 16 }}>
                <i data-lucide={ic} style={{ width: 22, height: 22 }}></i>
              </span>
              <h3 className="h3" style={{ fontSize: 'var(--fs-h4)', marginBottom: 8 }}>{label}</h3>
              <p className="muted" style={{ margin: 0, fontSize: 15.5, lineHeight: 1.6 }}>{detail}</p>
            </Card>
          ))}
        </div>
      </div>
    </section>
  );
}

function GalleryTeaser() {
  const { openLightbox } = useShell();
  const shots = [
    { src: IMG.exterior1, label: 'The cottage' },
    { src: IMG.kitchen, label: 'Kitchen' },
    { src: IMG.garden2, label: 'Garden' },
    { src: IMG.dining, label: 'Dining room' },
    { src: IMG.pond, label: 'The pond' },
    { src: IMG.woodDen, label: 'Wood den' },
  ];
  return (
    <section className="section">
      <div className="container">
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 28, flexWrap: 'wrap', gap: 16 }}>
          <div style={{ flex: '1 1 auto', minWidth: 0 }}>
            <Eyebrow>Gallery</Eyebrow>
            <h2 className="h2" style={{ margin: '14px 0 0' }}>Spacious gardens, set in private woodland</h2>
          </div>
          <Button variant="secondary" size="md" as="a" href="gallery" style={{ flexShrink: 0 }}>See all photos</Button>
        </div>
        <div className="gk-photos" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gridAutoRows: '180px', gap: 12 }}>
          <div style={{ gridColumn: 'span 2', gridRow: 'span 2' }}><Photo src={IMG.exterior1} label="The cottage" ratio="auto" radius={14} style={{ height: '100%', aspectRatio: 'auto' }} onClick={() => openLightbox(shots, 0)} /></div>
          {shots.slice(1, 5).map((s, i) => <Photo key={i} src={s.src} label={s.label} ratio="auto" radius={14} style={{ height: '100%', aspectRatio: 'auto' }} onClick={() => openLightbox(shots, i + 1)} />)}
        </div>
      </div>
    </section>
  );
}

function Reviews() {
  const quotes = [
    ['One of the loveliest places we have ever stayed — cosy and characterful, with a stunning garden and an abundance of woodland wildlife. We had the whole place to ourselves, apart from the many birds at the feeders.', 'JP', 'A winter woodland paradise · Jan 2026'],
    ["Such a beautiful, secluded location. A week of sunny weather made it ideal for sitting out and listening to nature, a BBQ and the occasional glass of wine. We all loved it — just how life should be.", 'Mark Rawlinson', 'Idyllic · Sep 2025'],
    ['We saw deer, buzzard and woodpeckers in the wood, with plenty of birds on the feeders. Just stopping to listen to the sounds of nature was wonderful. I couldn’t recommend it more.', 'William Ripper', 'Perfect for Easter · Apr 2025'],
  ];
  const live = useReviews();
  const liveQuotes = (live || []).map((r) => [r.body, r.name, (r.title ? r.title + ' · ' : '') + reviewMonth(r.date), r.rating || 5]);
  const shown = (liveQuotes.length ? liveQuotes : quotes.map(([q, who, when]) => [q, who, when, 5])).slice(0, 3);
  const stats = reviewStats(live);
  return (
    <section className="section section--soft">
      <div className="container">
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16, marginBottom: 32, flexWrap: 'wrap' }}>
          <div style={{ flex: '1 1 auto', minWidth: 0 }}>
            <Eyebrow>Guest reviews</Eyebrow>
            <h2 className="h2" style={{ margin: '14px 0 0' }}>What our guests say</h2>
          </div>
          {stats.count > 0 && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10, flexShrink: 0 }}><Rating value={stats.average} count={stats.count} /></span>}
        </div>
        <div className="grid grid-3">
          {shown.map(([q, who, when, rating], i) => (
            <Card key={i + who} padding="md">
              <Rating value={rating} showValue={false} />
              <p style={{ fontFamily: 'var(--font-display)', fontSize: 18, lineHeight: 1.55, color: 'var(--text-strong)', margin: '14px 0 18px' }}>“{q}”</p>
              <div style={{ fontSize: 14, color: 'var(--text-muted)' }}><b style={{ color: 'var(--text-strong)' }}>{who}</b> · {when}</div>
            </Card>
          ))}
        </div>
        <div style={{ marginTop: 28 }}><Button variant="secondary" size="md" as="a" href="reviews">{stats.count > 0 ? 'Read all ' + stats.count + ' reviews' : 'Read our reviews'}</Button></div>
      </div>
    </section>
  );
}

function ExploreTeaser() {
  const cards = [
    [IMG.stroll, 'Walks & birdwatching', 'Minsmere, Dunwich Heath and miles of quiet trails from the door.'],
    [IMG.aerial, 'Southwold & the coast', 'The pier, the lighthouse, fish & chips and Adnams, 20 minutes away.'],
    [IMG.pond, 'Proper Suffolk pubs', 'The White Hart, The Eels Foot and more — our local favourites.'],
  ];
  return (
    <section className="section">
      <div className="container">
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 28, flexWrap: 'wrap', gap: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 22, flex: '1 1 auto', minWidth: 0 }}>
            <a href="explore" aria-label="Southwold beach — a 15 minute drive from the cottage"
              style={{ flexShrink: 0, display: 'block', lineHeight: 0 }}>
              <img src={IMG.beach15} alt="Southwold seafront — a 15 minute drive from the cottage"
                width="118" height="118"
                style={{ width: 118, height: 118, borderRadius: '50%', objectFit: 'cover',
                  border: '4px solid #fff', boxShadow: '0 10px 26px rgba(24,40,22,0.18)',
                  transform: 'rotate(-4deg)' }} />
            </a>
            <div style={{ minWidth: 0 }}>
              <Eyebrow>Explore Suffolk</Eyebrow>
              <h2 className="h2" style={{ margin: '14px 0 0' }}>Wonderful things on your doorstep</h2>
            </div>
          </div>
          <Button variant="secondary" size="md" as="a" href="explore" style={{ flexShrink: 0 }}>See our selected attractions</Button>
        </div>
        <div className="grid grid-3">
          {cards.map(([src, title, desc]) => (
            <a key={title} href="explore" style={{ textDecoration: 'none' }}>
              <Card interactive>
                <Photo src={src} ratio="16 / 10" />
                <div style={{ padding: 'var(--space-6)' }}>
                  <h3 className="h3" style={{ fontSize: 'var(--fs-h4)', marginBottom: 8 }}>{title}</h3>
                  <p className="muted" style={{ margin: 0, fontSize: 15.5 }}>{desc}</p>
                </div>
              </Card>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

function OfferBanner() {
  const { openBooking } = useShell();
  return (
    <section className="section--tight" style={{ background: 'var(--surface-dark)' }}>
      <div className="container" style={{ display: 'flex', alignItems: 'center', gap: 30, flexWrap: 'wrap', padding: '40px 32px' }}>
        <div style={{ flex: '1 1 380px' }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--accent-sage)' }}>Special offer</span>
          <h2 className="h2" style={{ color: '#fff', margin: '12px 0 8px' }}>Second week half price, off-season</h2>
          <p style={{ color: '#d8cdba', margin: 0, fontSize: 16 }}>Book two consecutive weeks outside the peak season and the second week is half price. Perfect for a proper, unhurried woodland retreat.</p>
        </div>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <Button variant="on-dark" size="lg" as="a" href="offers">View offers</Button>
          <Button variant="primary" size="lg" onClick={openBooking}>Check availability</Button>
        </div>
      </div>
    </section>
  );
}

function FinalCTA() {
  const { openBooking } = useShell();
  return (
    <section className="section" style={{ textAlign: 'center' }}>
      <div className="container container--narrow">
        <div style={{ display: 'flex', justifyContent: 'center' }}><Eyebrow>Your woodland stay awaits</Eyebrow></div>
        <h2 className="h1" style={{ margin: '16px 0 14px' }}>Come and have the wood to yourselves</h2>
        <p className="lead muted" style={{ marginBottom: 28 }}>Breaks of three nights or more from £130 per night. Check the dates you'd like and we'll confirm the price and hold them for you.</p>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <Button variant="primary" size="lg" onClick={openBooking}>Check rates &amp; reserve</Button>
          <Button variant="secondary" size="lg" as="a" href={'tel:' + window.GKContact.PHONE.replace(/\s/g, '')}>Call Nick: {window.GKContact.PHONE}</Button>
        </div>
      </div>
    </section>
  );
}

function HomeContent() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useEffect(() => { applyAccent(t.accent); }, [t.accent]);
  return (
    <React.Fragment>
      <Hero t={t} />
      <TrustStrip />
      <Story />
      <WhyStay />
      <GalleryTeaser />
      <Reviews />
      <ExploreTeaser />
      {t.showOffer && <OfferBanner />}
      <FinalCTA />
      <TweaksPanel title="Tweaks">
        <TweakSection label="Hero" />
        <TweakRadio label="Hero direction" value={t.hero} options={['centered', 'panel', 'split']} onChange={(v) => setTweak('hero', v)} />
        <TweakText label="CTA wording" value={t.cta} onChange={(v) => setTweak('cta', v)} />
        <TweakSection label="Theme" />
        <TweakColor label="Accent green" value={t.accent} options={['#2f5d3a', '#3f6b32', '#4a6b57']} onChange={(v) => setTweak('accent', v)} />
        <TweakToggle label="Show offer banner" value={t.showOffer} onChange={(v) => setTweak('showOffer', v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

window.GKmount('/', HomeContent);
