const { useState, useEffect } = React;

// ============================================================
// PALETTES — swap via Tweaks panel
// ============================================================
const PALETTES = {
  'coal-saffron': {
    label: 'Coal & Saffron',
    bgDark: '#181614', bgDarkMid: '#22201D', bgDarkSoft: '#3A3631',
    green: '#827254',
    accent: '#D4A24C', accentDeep: '#B0822D', accent2: '#E8C170',
    paper: '#F0E9D8', paperWarm: '#E4DBC3',
    ink: '#1B1812', inkSoft: '#3D3729', inkMute: '#7A7059'
  },
  'plum-sand': {
    label: 'Plum & Sand',
    bgDark: '#2B1929', bgDarkMid: '#3A2238', bgDarkSoft: '#54405C',
    green: '#9C7E8E',
    accent: '#B97A6B', accentDeep: '#8E5A4D', accent2: '#D9A89A',
    paper: '#EFE5D0', paperWarm: '#E3D8BE',
    ink: '#2A1B27', inkSoft: '#4A3744', inkMute: '#7A6A73'
  },
  'slate-marigold': {
    label: 'Slate & Marigold',
    bgDark: '#2B2A28', bgDarkMid: '#3A3835', bgDarkSoft: '#54514C',
    green: '#9C9384',
    accent: '#D67930', accentDeep: '#A75A1B', accent2: '#EAA960',
    paper: '#EEE8DA', paperWarm: '#E2DBC8',
    ink: '#1F1D1A', inkSoft: '#3C3934', inkMute: '#6F6A60'
  },
  'burgundy-brass': {
    label: 'Burgundy & Brass',
    bgDark: '#2E1418', bgDarkMid: '#3F1D21', bgDarkSoft: '#5C2F33',
    green: '#A89472',
    accent: '#A88A4A', accentDeep: '#85692E', accent2: '#C9AC74',
    paper: '#EEE5D0', paperWarm: '#E1D6BC',
    ink: '#1F1410', inkSoft: '#3F2C26', inkMute: '#75665A'
  },
  'ink-cobalt': {
    label: 'Ink & Cobalt',
    bgDark: '#15161A', bgDarkMid: '#1F2027', bgDarkSoft: '#363845',
    green: '#7A8395',
    accent: '#2E5BAE', accentDeep: '#1F3F82', accent2: '#6B8DD6',
    paper: '#EDE7D5', paperWarm: '#E0DAC6',
    ink: '#15161A', inkSoft: '#2F313D', inkMute: '#666876'
  }
};

function applyPalette(name) {
  const p = PALETTES[name] || PALETTES['coal-saffron'];
  const r = document.documentElement.style;
  r.setProperty('--forest-deep', p.bgDark);
  r.setProperty('--forest',      p.bgDarkMid);
  r.setProperty('--forest-mist', p.bgDarkSoft);
  r.setProperty('--moss',        p.green);
  r.setProperty('--terra',       p.accent);
  r.setProperty('--terra-deep',  p.accentDeep);
  r.setProperty('--terra-soft',  p.accent2);
  r.setProperty('--amber',       p.accent2);
  r.setProperty('--amber-soft',  p.accent2);
  r.setProperty('--stone-50',    p.paper);
  r.setProperty('--stone-100',   p.paperWarm);
  r.setProperty('--paper',       p.paper);
  r.setProperty('--ink',         p.ink);
  r.setProperty('--ink-soft',    p.inkSoft);
  r.setProperty('--ink-mute',    p.inkMute);
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "ink-cobalt"
}/*EDITMODE-END*/;

function Nav({ onBook, user, onSignIn, onSignOut, onMyHikes }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = React.useRef(null);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    if (!menuOpen) return;
    const onDocClick = (e) => { if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false); };
    document.addEventListener('mousedown', onDocClick);
    return () => document.removeEventListener('mousedown', onDocClick);
  }, [menuOpen]);

  const initial = user ? (user.name || user.email || '?')[0].toUpperCase() : '';

  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-inner">
        <a href="#top" className="nav-logo">
          <div className="nav-logo-mark">S</div>
          <div>
            <div className="nav-logo-text">Sorrento Hiking</div>
            <div className="nav-logo-tagline">Est. Sorrento Peninsula</div>
          </div>
        </a>
        <div className="nav-links">
          <a href="#paths" className="nav-link">Paths</a>
          <a href="#experiences" className="nav-link">Experiences</a>
          <a href="#story" className="nav-link">Our Story</a>
          <a href="#guides" className="nav-link">Guides</a>
          {user ? (
            <div className="user-menu" ref={menuRef}>
              <button
                className="user-trigger always"
                onClick={() => setMenuOpen(o => !o)}
                aria-haspopup="menu"
                aria-expanded={menuOpen}
              >
                <span className="user-avatar">{initial}</span>
                <span className="user-name">{user.name || user.email}</span>
                <Icon.Chevron style={{ width: 14, height: 14 }} />
              </button>
              {menuOpen && (
                <div className="user-dropdown" role="menu">
                  <div className="user-dropdown-meta">
                    <div className="user-dropdown-name">{user.name}</div>
                    <div className="user-dropdown-email">{user.email}</div>
                  </div>
                  <button className="user-dropdown-item" onClick={() => { setMenuOpen(false); onMyHikes(); }}>
                    <Icon.Calendar style={{ width: 16, height: 16 }} />
                    My hikes
                  </button>
                  <button className="user-dropdown-item" onClick={() => { setMenuOpen(false); onBook(); }}>
                    <Icon.Arrow style={{ width: 16, height: 16 }} />
                    Book a hike
                  </button>
                  <button className="user-dropdown-item danger" onClick={() => { setMenuOpen(false); onSignOut(); }}>
                    Sign out
                  </button>
                </div>
              )}
            </div>
          ) : (
            <button className="nav-link nav-signin always" onClick={onSignIn}>
              <Icon.User style={{ width: 16, height: 16 }} />
              Sign in
            </button>
          )}
          <button className="nav-cta always" onClick={onBook}>Book a Hike</button>
        </div>
      </div>
    </nav>
  );
}

function AuthModal({ open, mode, onClose, onModeChange, onAuthed }) {
  const { signup, login } = useAuth();
  const [form, setForm] = useState({ name: '', email: '', password: '' });
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (open) { setError(''); setForm({ name: '', email: '', password: '' }); }
  }, [open, mode]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) {
      document.body.style.overflow = 'hidden';
      window.addEventListener('keydown', onKey);
    }
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [open, onClose]);

  const submit = (e) => {
    e.preventDefault();
    setError(''); setBusy(true);
    try {
      const user = mode === 'signup' ? signup(form) : login(form);
      setBusy(false);
      onAuthed && onAuthed(user);
    } catch (err) {
      setBusy(false);
      setError(err.message || 'Something went wrong.');
    }
  };

  const isSignup = mode === 'signup';

  return (
    <div className={`booking ${open ? 'open' : ''}`} onClick={onClose}>
      <div className="booking-card auth-card" onClick={e => e.stopPropagation()}>
        <button className="booking-close" onClick={onClose} aria-label="Close">
          <Icon.Close style={{ width: 18, height: 18 }} />
        </button>
        <div className="booking-eyebrow">{isSignup ? 'New traveller' : 'Welcome back'}</div>
        <h2 className="booking-title">{isSignup ? 'Create an account' : 'Sign in'}</h2>
        <p className="booking-sub">
          {isSignup
            ? 'Save your bookings and keep track of every hike you join.'
            : 'Continue where you left off — your hikes are waiting.'}
        </p>
        <form onSubmit={submit}>
          {isSignup && (
            <div className="field">
              <label>Your name</label>
              <input
                type="text"
                value={form.name}
                onChange={e => setForm({ ...form, name: e.target.value })}
                placeholder="Maria Rossi"
                required
              />
            </div>
          )}
          <div className="field">
            <label>Email</label>
            <input
              type="email"
              value={form.email}
              onChange={e => setForm({ ...form, email: e.target.value })}
              placeholder="you@example.com"
              autoComplete="email"
              required
            />
          </div>
          <div className="field">
            <label>Password</label>
            <input
              type="password"
              value={form.password}
              onChange={e => setForm({ ...form, password: e.target.value })}
              placeholder={isSignup ? 'Choose a password' : 'Your password'}
              autoComplete={isSignup ? 'new-password' : 'current-password'}
              minLength={6}
              required
            />
          </div>
          {error && <div className="auth-error">{error}</div>}
          <button className="booking-submit" type="submit" disabled={busy}>
            {busy ? 'Just a moment…' : isSignup ? 'Create account' : 'Sign in'}
          </button>
        </form>
        <div className="auth-switch">
          {isSignup ? (
            <>Already have an account?{' '}
              <button type="button" className="auth-switch-link" onClick={() => onModeChange('signin')}>Sign in</button>
            </>
          ) : (
            <>New to Sorrento Hiking?{' '}
              <button type="button" className="auth-switch-link" onClick={() => onModeChange('signup')}>Create an account</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function MyHikesDrawer({ open, onClose, user, onBook, refreshKey }) {
  const [items, setItems] = useState([]);
  useEffect(() => {
    if (open && user) setItems(BookingStore.forUser(user.email).sort((a, b) => b.createdAt - a.createdAt));
  }, [open, user, refreshKey]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) {
      document.body.style.overflow = 'hidden';
      window.addEventListener('keydown', onKey);
    }
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [open, onClose]);

  const fmt = (iso) => {
    if (!iso) return '';
    try {
      const d = new Date(iso);
      return d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' });
    } catch (_) { return iso; }
  };

  return (
    <>
      <div className={`drawer-backdrop ${open ? 'open' : ''}`} onClick={onClose} />
      <aside className={`drawer my-hikes-drawer ${open ? 'open' : ''}`}>
        {open && user && (
          <>
            <div className="my-hikes-header">
              <div>
                <div className="drawer-eyebrow" style={{ color: 'var(--terra)' }}>Your account</div>
                <h2 className="drawer-title" style={{ color: 'var(--ink)' }}>My hikes</h2>
                <div className="my-hikes-subtitle">Signed in as <strong>{user.email}</strong></div>
              </div>
              <button className="drawer-close drawer-close-light" onClick={onClose} aria-label="Close">
                <Icon.Close style={{ width: 18, height: 18 }} />
              </button>
            </div>

            <div className="drawer-body" style={{ paddingTop: 24 }}>
              {items.length === 0 ? (
                <div className="my-hikes-empty">
                  <div className="my-hikes-empty-icon"><Icon.Calendar style={{ width: 28, height: 28 }} /></div>
                  <h3>No hikes booked yet.</h3>
                  <p>Pick a path and reserve your spot — your bookings will land here.</p>
                  <button className="btn btn-primary" onClick={() => { onClose(); onBook(); }} style={{ margin: '0 auto' }}>
                    Book a hike <Icon.Arrow />
                  </button>
                </div>
              ) : (
                <div className="my-hikes-list">
                  {items.map(b => (
                    <div className="my-hike-item" key={b.id}>
                      <div className="my-hike-top">
                        <div>
                          <div className="my-hike-eyebrow">№ {String(items.length - items.indexOf(b)).padStart(2, '0')} · Booking</div>
                          <h3 className="my-hike-name">{b.path}</h3>
                        </div>
                        <span className={`my-hike-status status-${b.status || 'pending'}`}>{b.status || 'pending'}</span>
                      </div>
                      <div className="my-hike-meta">
                        <div><span>Date</span><strong>{fmt(b.date)}</strong></div>
                        <div><span>People</span><strong>{b.people}</strong></div>
                        <div><span>Requested</span><strong>{fmt(new Date(b.createdAt).toISOString().slice(0,10))}</strong></div>
                      </div>
                      {b.notes && <div className="my-hike-notes">"{b.notes}"</div>}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </>
        )}
      </aside>
    </>
  );
}

function Hero({ onBook, onExplore }) {
  return (
    <section className="hero" id="top">
      <div className="hero-bg" />
      <div className="hero-bg-image" />
      <div className="hero-vignette" />

      <div className="container hero-content">
        <div className="hero-eyebrow-row">
          <span className="line" />
          <span className="eyebrow on-dark">The Professionals of "The Path of the Gods"</span>
        </div>
        <h1 className="hero-title">
          Changing tourists into <span className="accent">travellers.</span>
        </h1>
        <p className="hero-sub">
          A small collective of local guides leading you across the ancient mule tracks, beech forests, and Roman ruins of the Sorrento Peninsula and Amalfi Coast — between the Gulf of Naples and the Gulf of Salerno.
        </p>
        <div className="hero-actions">
          <button className="btn btn-primary" onClick={onBook}>
            Book a hike
            <Icon.Arrow />
          </button>
          <button className="btn btn-ghost" onClick={onExplore}>
            See the seven paths
          </button>
        </div>
      </div>

      <div className="hero-meta">
        <div className="hero-meta-line">— 7 paths · 2 experiences</div>
        <div className="hero-meta-line">— Decades of local knowledge</div>
        <div className="hero-meta-line">— Sea level → 1,444 m</div>
      </div>

      <div className="hero-scroll">
        <span>Scroll</span>
        <div className="hero-scroll-line" />
      </div>
    </section>
  );
}

function PathCard({ path, index, onOpen }) {
  return (
    <article
      className={`path-card reveal ${path.feature ? 'feature' : ''}`}
      data-tone={path.tone}
      onClick={() => onOpen(path)}
      style={{ transitionDelay: `${(index % 3) * 60}ms` }}
    >
      <div className="path-image-wrap">
        <SmartImage src={path.image} alt={path.name} tone={path.tone} label={path.placeholderLabel} className="path-image" />
        <div className="path-image-tint" />
        <div className="path-image-overlay">
          <div className="path-difficulty" data-level={path.stats.difficulty.replace(/\s/g,'')}>
            <span className="dot" />
            <span>{path.stats.difficulty}</span>
          </div>
          <div className="path-num">№ {path.num}</div>
        </div>
      </div>
      <div className="path-body">
        <div className="path-eyebrow">{path.eyebrow}</div>
        <h3 className="path-name">{path.name}</h3>
        <div className="path-tagline">"{path.tagline}"</div>
        <div className="path-stats">
          <div className="path-stat">
            <span className="path-stat-label">Distance</span>
            <span className="path-stat-value">{path.stats.distance}</span>
          </div>
          <div className="path-stat">
            <span className="path-stat-label">Terrain</span>
            <span className="path-stat-value">{path.stats.terrain}</span>
          </div>
        </div>
      </div>
    </article>
  );
}

function PathsSection({ onOpenPath }) {
  return (
    <section className="section paths-section" id="paths">
      <div className="container">
        <div className="section-header reveal">
          <div>
            <h2 className="section-title">
              Seven routes across the <span className="accent">SyrenLand.</span>
            </h2>
          </div>
          <p className="section-intro">
            From a 4 km descent through old paper mills to a 7.5 km loop at 650 m above the sea, every path is led by a guide who chose this ridge as their home.
          </p>
        </div>

        <div className="paths-grid">
          {window.PATHS.map((p, i) => (
            <PathCard key={p.id} path={p} index={i} onOpen={onOpenPath} />
          ))}
        </div>
      </div>
    </section>
  );
}

function ExperienceCard({ exp, onOpen }) {
  return (
    <article className="experience-card reveal" onClick={() => onOpen(exp)}>
      <SmartImage src={exp.image} alt={exp.name} tone="amber" label={exp.placeholderLabel} className="experience-image" />
      <div className="experience-body">
        <span className="experience-eyebrow">№ {exp.num} · Experience</span>
        <h3 className="experience-name">{exp.name}</h3>
        <div className="experience-tagline">"{exp.tagline}"</div>
        <span className="experience-cta">Learn more <Icon.Arrow /></span>
      </div>
    </article>
  );
}

function ExperiencesSection({ onOpen }) {
  return (
    <section className="section experiences-section" id="experiences">
      <div className="container">
        <div className="section-header reveal">
          <div>
            <h2 className="section-title">Beyond the path. <span className="accent">The essence.</span></h2>
          </div>
          <p className="section-intro">
            Two slower experiences for travellers who want to taste the peninsula — a sunset told as myth, and a town walk through the lemon groves and old factories of Sorrento.
          </p>
        </div>

        <div className="experiences-grid">
          {window.EXPERIENCES.map(exp => (
            <ExperienceCard key={exp.id} exp={exp} onOpen={onOpen} />
          ))}
        </div>
      </div>
    </section>
  );
}

function StorySection() {
  return (
    <section className="section story-section" id="story">
      <div className="container">
        <div className="story-grid">
          <div className="story-image-stack reveal">
            <div className="story-img story-img-1">
              <SmartImage src="images/path_of_gods/sentiero04.jpg" alt="On the path" tone="forest" label="On the path" />
            </div>
            <div className="story-img story-img-2">
              <SmartImage src="images/minervas_hike/campanella_03.jpg" alt="Punta Campanella" tone="terra" label="Punta Campanella" />
            </div>
            <div className="story-img-caption">Field documentation · Vol. I</div>
          </div>

          <div className="story-text reveal">
            <span className="eyebrow">Who we are</span>
            <h2 className="story-title">
              A handful of locals who never quite left the <span className="accent">ridge.</span>
            </h2>
            <p>
              Sorrento Hiking is a small group of guides united by a shared affection for the nature, traditions, and customs of the Sorrento Peninsula and the Amalfi Coast. Between us we speak several languages and have decades of experience reading these mule tracks in every season.
            </p>
            <p>
              We aren't an agency. We meet you in Tasso Square, drive you to the trailhead, and walk slowly enough that you'll notice the orchids in spring, the kestrels overhead, and the way the basolato underfoot is the same stone Greeks set in the 4th century BC.
            </p>

            <div className="story-stats">
              <div>
                <div className="story-stat-num">7</div>
                <div className="story-stat-lbl">Paths</div>
              </div>
              <div>
                <div className="story-stat-num">4</div>
                <div className="story-stat-lbl">Local Guides</div>
              </div>
              <div>
                <div className="story-stat-num">650<span style={{ fontSize: '20px', verticalAlign: 'super' }}>m</span></div>
                <div className="story-stat-lbl">Above the Sea</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function GuideCard({ guide }) {
  return (
    <div className="guide-card reveal">
      <div className="guide-portrait">{guide.name[0]}</div>
      <div>
        <div className="eyebrow" style={{ marginBottom: 6 }}>Guide</div>
        <h3 className="guide-name">{guide.name}</h3>
      </div>
      <p className="guide-quote">"{guide.quote}"</p>
      <div className="guide-contact">
        <Icon.Whatsapp />
        <span>{guide.phone}</span>
      </div>
    </div>
  );
}

function GuidesSection() {
  return (
    <section className="section guides-section" id="guides">
      <div className="container">
        <div className="section-header reveal">
          <div>
            <h2 className="section-title">Four people. <span className="accent">One ridge.</span></h2>
          </div>
          <p className="section-intro">
            Reach any of us directly on WhatsApp. We answer in English, Italian, and a few other languages — and we'll always tell you honestly which route fits the day's weather.
          </p>
        </div>

        <div className="guides-grid">
          {window.GUIDES.map(g => <GuideCard key={g.name} guide={g} />)}
        </div>
      </div>
    </section>
  );
}

function PathDrawer({ path, onClose, onBook }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (path) {
      document.body.style.overflow = 'hidden';
      window.addEventListener('keydown', onKey);
    }
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [path, onClose]);

  return (
    <>
      <div className={`drawer-backdrop ${path ? 'open' : ''}`} onClick={onClose} />
      <aside className={`drawer ${path ? 'open' : ''}`}>
        {path && (
          <>
            <div className="drawer-hero">
              <SmartImage src={path.image} alt={path.name} tone={path.tone} label={path.placeholderLabel} />
              <button className="drawer-close" onClick={onClose} aria-label="Close">
                <Icon.Close style={{ width: 18, height: 18 }} />
              </button>
              <div className="drawer-hero-content">
                <div className="drawer-eyebrow">№ {path.num} · {path.eyebrow}</div>
                <h2 className="drawer-title">{path.name}</h2>
                <div className="drawer-tagline">"{path.tagline}"</div>
              </div>
            </div>

            <div className="drawer-body">
              <div className="drawer-meta-row">
                <div>
                  <div className="drawer-meta-label">Distance</div>
                  <div className="drawer-meta-value">{path.stats.distance}</div>
                </div>
                <div>
                  <div className="drawer-meta-label">Difficulty</div>
                  <div className="drawer-meta-value">{path.stats.difficulty}</div>
                </div>
                <div>
                  <div className="drawer-meta-label">Terrain</div>
                  <div className="drawer-meta-value">{path.stats.terrain}</div>
                </div>
                <div>
                  <div className="drawer-meta-label">Group</div>
                  <div className="drawer-meta-value">2 – 12</div>
                </div>
              </div>

              <div className="drawer-section">
                <div className="drawer-section-title">About the Path</div>
                <p>{path.intro}</p>
              </div>

              <div className="drawer-section">
                <div className="drawer-section-title">Route Options</div>
                <div className="drawer-route-options">
                  {path.routes.map((r, i) => (
                    <div className="drawer-route" key={i}>
                      <div className="drawer-route-name">{r.name}</div>
                      <div className="drawer-route-path">{r.path}</div>
                      <div className="drawer-route-stats">
                        <div className="drawer-route-stat">Distance: <strong>{r.distance}</strong></div>
                        <div className="drawer-route-stat">Difficulty: <strong>{r.difficulty}</strong></div>
                        <div className="drawer-route-stat">Meet: <strong>{r.meeting}</strong></div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="drawer-section">
                <div className="drawer-section-title">Highlights</div>
                <div className="tags">
                  {path.highlights.map(h => <span className="tag" key={h}>{h}</span>)}
                </div>
              </div>

              <div className="drawer-section">
                <div className="drawer-section-title">Botany</div>
                <div className="tags">
                  {path.botany.map(b => <span className="tag" key={b}>{b}</span>)}
                </div>
              </div>

              <div className="drawer-section">
                <div className="drawer-section-title">Fauna</div>
                <div className="tags">
                  {path.fauna.map(f => <span className="tag" key={f}>{f}</span>)}
                </div>
              </div>
            </div>

            <div className="drawer-cta">
              <div className="drawer-cta-meta">
                Meeting point — <strong>{path.routes[0].meeting}</strong>
              </div>
              <button className="btn btn-primary" onClick={() => onBook(path)}>
                Book this hike
                <Icon.Arrow />
              </button>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

function BookingModal({ open, onClose, prefilledPath, user, onRequireAuth, onBooked }) {
  const [stage, setStage] = useState('form');
  const [form, setForm] = useState({ name: '', email: '', date: '', people: 2, path: prefilledPath?.name || '', notes: '' });

  useEffect(() => {
    if (open) {
      setStage('form');
      setForm(f => ({
        ...f,
        name: user?.name || '',
        email: user?.email || '',
        path: prefilledPath?.name || f.path || ''
      }));
    }
  }, [open, prefilledPath, user]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) {
      document.body.style.overflow = 'hidden';
      window.addEventListener('keydown', onKey);
    }
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [open, onClose]);

  const submit = (e) => {
    e.preventDefault();
    if (!user) { onRequireAuth && onRequireAuth(); return; }
    const record = BookingStore.add({
      userEmail: user.email,
      path: form.path,
      date: form.date,
      people: Number(form.people) || 1,
      notes: form.notes,
      status: 'pending'
    });
    setStage('success');
    onBooked && onBooked(record);
  };

  return (
    <div className={`booking ${open ? 'open' : ''}`} onClick={onClose}>
      <div className="booking-card" onClick={e => e.stopPropagation()}>
        <button className="booking-close" onClick={onClose} aria-label="Close">
          <Icon.Close style={{ width: 18, height: 18 }} />
        </button>
        {stage === 'form' && (
          <>
            <div className="booking-eyebrow">Reserve your spot</div>
            <h2 className="booking-title">Book a hike</h2>
            <p className="booking-sub">We'll confirm by email within 24 hours. Full refund 30+ days out.</p>
            {!user && (
              <div className="auth-hint">
                <span>You'll need an account to confirm.</span>
                <button type="button" className="auth-switch-link" onClick={onRequireAuth}>Sign in or create one →</button>
              </div>
            )}
            <form onSubmit={submit}>
              <div className="field">
                <label>Path</label>
                <select value={form.path} onChange={e => setForm({ ...form, path: e.target.value })} required>
                  <option value="">Choose a path</option>
                  {window.PATHS.map(p => <option key={p.id} value={p.name}>{p.name}</option>)}
                  {window.EXPERIENCES.map(p => <option key={p.id} value={p.name}>{p.name}</option>)}
                </select>
              </div>
              <div className="field-row">
                <div className="field">
                  <label>Date</label>
                  <input type="date" value={form.date} onChange={e => setForm({ ...form, date: e.target.value })} required />
                </div>
                <div className="field">
                  <label>People</label>
                  <input type="number" min="1" max="12" value={form.people} onChange={e => setForm({ ...form, people: e.target.value })} required />
                </div>
              </div>
              <div className="field">
                <label>Your name</label>
                <input
                  type="text"
                  value={form.name}
                  onChange={e => setForm({ ...form, name: e.target.value })}
                  readOnly={!!user}
                  required
                />
              </div>
              <div className="field">
                <label>Email</label>
                <input
                  type="email"
                  value={form.email}
                  onChange={e => setForm({ ...form, email: e.target.value })}
                  readOnly={!!user}
                  required
                />
              </div>
              <div className="field">
                <label>Anything we should know? (optional)</label>
                <textarea rows="2" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} />
              </div>
              <button className="booking-submit" type="submit">
                {user ? 'Request booking' : 'Sign in to continue'}
              </button>
            </form>
          </>
        )}
        {stage === 'success' && (
          <div className="booking-success">
            <div className="booking-success-icon"><Icon.Check style={{ width: 28, height: 28 }} /></div>
            <h3>Grazie, {form.name.split(' ')[0] || 'traveller'}.</h3>
            <p style={{ color: 'var(--ink-mute)', marginBottom: 24 }}>
              We've received your request for <strong style={{ color: 'var(--terra)' }}>{form.path}</strong> on {form.date}. A guide will reply within 24 hours.
            </p>
            <button className="btn btn-primary" onClick={onClose} style={{ margin: '0 auto' }}>Continue exploring</button>
          </div>
        )}
      </div>
    </div>
  );
}

function Footer({ onBook }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-top">
          <div>
            <div className="footer-brand-mark">Sorrento <span className="accent">Hiking.</span></div>
            <div className="footer-tagline">"Changing tourists into travellers."</div>
            <div className="footer-coords">
              80067 Sorrento (NA), Italy<br />
              40°37′37″N · 14°22′28″E<br />
              Fulvio +39 339 649 6418<br />
              Nino +39 334 116 1642
            </div>
          </div>
          <div className="footer-col">
            <div className="footer-col-title">Paths</div>
            <ul>{window.PATHS.slice(0,5).map(p => <li key={p.id}>{p.name}</li>)}</ul>
          </div>
          <div className="footer-col">
            <div className="footer-col-title">Experiences</div>
            <ul>
              {window.EXPERIENCES.map(e => <li key={e.id}>{e.name}</li>)}
              <li>Custom itineraries</li>
              <li>Group bookings</li>
            </ul>
          </div>
          <div className="footer-col">
            <div className="footer-col-title">Info</div>
            <ul>
              <li>Who we are</li>
              <li>Terms & conditions</li>
              <li>Cancellation policy</li>
              <li>Weather forecast</li>
              <li onClick={onBook} style={{ color: 'var(--amber)' }}>Book now →</li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 Sorrento Hiking · All paths walked with permission of the land.</div>
          <div className="footer-socials">
            <a href="#" className="footer-social" aria-label="Instagram"><Icon.Instagram /></a>
            <a href="#" className="footer-social" aria-label="Facebook"><Icon.Facebook /></a>
          </div>
        </div>
      </div>
    </footer>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [openPath, setOpenPath] = useState(null);
  const [bookingOpen, setBookingOpen] = useState(false);
  const [bookingPath, setBookingPath] = useState(null);
  const [authOpen, setAuthOpen] = useState(false);
  const [authMode, setAuthMode] = useState('signin');
  const [myHikesOpen, setMyHikesOpen] = useState(false);
  const [bookingsVersion, setBookingsVersion] = useState(0);
  const { user, logout } = useAuth();

  useReveal();

  useEffect(() => { applyPalette(t.palette); }, [t.palette]);

  useEffect(() => {
    const urls = [
      ...window.PATHS.map(p => p.image),
      ...window.EXPERIENCES.map(e => e.image),
      'images/path_of_gods/sentiero04.jpg',
      'images/minervas_hike/campanella_03.jpg'
    ];
    urls.filter(Boolean).forEach(src => { const img = new Image(); img.src = src; });
  }, []);

  const handleOpenPath = (p) => setOpenPath(p);
  const handleCloseDrawer = () => setOpenPath(null);
  const handleBookFromDrawer = (p) => { setBookingPath(p); setOpenPath(null); setTimeout(() => setBookingOpen(true), 250); };
  const handleOpenBooking = () => { setBookingPath(null); setBookingOpen(true); };
  const handleOpenExperience = (exp) => { setBookingPath(exp); setBookingOpen(true); };
  const scrollPaths = () => document.getElementById('paths').scrollIntoView({ behavior: 'smooth', block: 'start' });

  const openAuth = (mode = 'signin') => { setAuthMode(mode); setAuthOpen(true); };
  const handleRequireAuth = () => { setBookingOpen(false); setTimeout(() => openAuth('signup'), 200); };
  const handleAuthed = () => {
    setAuthOpen(false);
    if (bookingPath || bookingOpen) setTimeout(() => setBookingOpen(true), 200);
  };
  const handleSignOut = () => { logout(); setMyHikesOpen(false); };
  const handleBooked = () => setBookingsVersion(v => v + 1);

  const paletteOptions = Object.keys(PALETTES).map(k => ({
    value: k,
    palette: [PALETTES[k].bgDark, PALETTES[k].accent, PALETTES[k].paper, PALETTES[k].accent2]
  }));

  return (
    <>
      <Nav
        onBook={handleOpenBooking}
        user={user}
        onSignIn={() => openAuth('signin')}
        onSignOut={handleSignOut}
        onMyHikes={() => setMyHikesOpen(true)}
      />
      <Hero onBook={handleOpenBooking} onExplore={scrollPaths} />
      <PathsSection onOpenPath={handleOpenPath} />
      <StorySection />
      <ExperiencesSection onOpen={handleOpenExperience} />
      <GuidesSection />
      <Footer onBook={handleOpenBooking} />
      <PathDrawer path={openPath} onClose={handleCloseDrawer} onBook={handleBookFromDrawer} />
      <BookingModal
        open={bookingOpen}
        onClose={() => setBookingOpen(false)}
        prefilledPath={bookingPath}
        user={user}
        onRequireAuth={handleRequireAuth}
        onBooked={handleBooked}
      />
      <AuthModal
        open={authOpen}
        mode={authMode}
        onClose={() => setAuthOpen(false)}
        onModeChange={setAuthMode}
        onAuthed={handleAuthed}
      />
      <MyHikesDrawer
        open={myHikesOpen}
        onClose={() => setMyHikesOpen(false)}
        user={user}
        onBook={handleOpenBooking}
        refreshKey={bookingsVersion}
      />

      <TweaksPanel>
        <TweakSection label="Color Palette" />
        <div style={{ display: 'grid', gap: 6 }}>
          {Object.keys(PALETTES).map(key => {
            const p = PALETTES[key];
            const active = t.palette === key;
            return (
              <button
                key={key}
                onClick={() => setTweak('palette', key)}
                style={{
                  display: 'grid',
                  gridTemplateColumns: '52px 1fr',
                  gap: 10,
                  alignItems: 'center',
                  padding: '6px 8px',
                  border: active ? '1.5px solid #29261b' : '1px solid rgba(0,0,0,0.12)',
                  borderRadius: 8,
                  background: active ? 'rgba(0,0,0,0.05)' : 'transparent',
                  cursor: 'pointer',
                  textAlign: 'left',
                  font: 'inherit',
                  color: '#29261b'
                }}
              >
                <div style={{ display: 'flex', borderRadius: 4, overflow: 'hidden', height: 28, border: '1px solid rgba(0,0,0,0.08)' }}>
                  <div style={{ flex: 1.4, background: p.bgDark }} />
                  <div style={{ flex: 1, background: p.accent }} />
                  <div style={{ flex: 0.6, background: p.accent2 }} />
                  <div style={{ flex: 1, background: p.paper }} />
                </div>
                <div style={{ fontSize: 12, fontWeight: 500 }}>{p.label}</div>
              </button>
            );
          })}
        </div>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
