// Public pages: Tours listing, Tour detail, Vehicles, Blog, Page, Contact

// -------- TOURS LISTING --------
const PublicTours = ({ state, navigate }) => {
  const [category, setCategory] = useState('all');
  const [sort, setSort] = useState('featured');
  const [priceRange, setPriceRange] = useState('any');
  const [durationFilter, setDurationFilter] = useState('any');
  const [destFilter, setDestFilter] = useState('all');
  const [page, setPage] = useState(1);
  const perPage = 8;

  const destinations = ['all', ...new Set(state.packages.filter(p => p.status === 'published').map(p => p.destination))];

  const list = state.packages
    .filter(p => p.status === 'published')
    .filter(p => category === 'all' || p.category === category)
    .filter(p => destFilter === 'all' || p.destination === destFilter)
    .filter(p => {
      if (priceRange === 'any') return true;
      if (priceRange === '<200') return p.priceFrom < 200;
      if (priceRange === '200-500') return p.priceFrom >= 200 && p.priceFrom <= 500;
      if (priceRange === '500-1500') return p.priceFrom > 500 && p.priceFrom <= 1500;
      return p.priceFrom > 1500;
    })
    .filter(p => {
      if (durationFilter === 'any') return true;
      if (durationFilter === 'half') return p.durationDays <= 0.5;
      if (durationFilter === 'day') return p.durationDays === 1;
      if (durationFilter === 'multi') return p.durationDays >= 2 && p.durationDays <= 3;
      return p.durationDays > 3;
    });

  const sorted = [...list].sort((a, b) => {
    if (sort === 'price-asc') return a.priceFrom - b.priceFrom;
    if (sort === 'price-desc') return b.priceFrom - a.priceFrom;
    if (sort === 'rating') return b.rating - a.rating;
    return (b.featured ? 1 : 0) - (a.featured ? 1 : 0);
  });

  const totalPages = Math.ceil(sorted.length / perPage) || 1;
  const paged = sorted.slice((page - 1) * perPage, page * perPage);

  return (
    <div style={{ background: 'var(--paper)', minHeight: '100vh' }}>
      <div style={{ background: 'var(--green-deep)', color: '#F5EEDE', padding: '28px 32px 64px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <PublicNav state={state} navigate={navigate} dark />
          <div style={{ marginTop: 48 }}>
            <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.12em', color: '#E85D2F' }}>Tour packages</div>
            <h1 style={{ fontSize: 64, letterSpacing: '-0.03em', marginTop: 8, fontWeight: 300 }}>All trips. <span style={{ fontStyle: 'italic' }}>Every season.</span></h1>
            <p style={{ fontSize: 16, marginTop: 12, maxWidth: 640, color: 'rgba(245,238,222,0.75)' }}>{state.packages.filter(p => p.status === 'published').length} packages · inbound Sarawak + outbound from Kuching.</p>
          </div>
        </div>
      </div>

      <div style={{ maxWidth: 1280, margin: '-32px auto 0', padding: '0 32px 80px' }}>
        {/* Filter bar */}
        <div style={{ background: 'white', borderRadius: 20, padding: 24, boxShadow: '0 10px 30px rgba(0,0,0,0.06)', border: '1px solid #e8e1cf', marginBottom: 32 }}>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 16 }}>
            {[['all', 'All', state.packages.filter(p => p.status === 'published').length], ['inbound', 'Inbound Sarawak', state.packages.filter(p => p.status === 'published' && p.category === 'inbound').length], ['outbound', 'Outbound', state.packages.filter(p => p.status === 'published' && p.category === 'outbound').length]].map(([k, label, count]) => (
              <button key={k} onClick={() => { setCategory(k); setPage(1); }}
                style={{ padding: '10px 18px', borderRadius: 999, fontSize: 14, fontWeight: 500, background: category === k ? 'var(--green-deep)' : 'transparent', color: category === k ? '#F5EEDE' : 'var(--ink)', border: category === k ? '1px solid var(--green-deep)' : '1px solid #e2dccb' }}>
                {label} <span style={{ opacity: 0.6, marginLeft: 4 }}>{count}</span>
              </button>
            ))}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 12 }}>
            <Select label="Destination" value={destFilter} onChange={setDestFilter} options={destinations.map(d => ({ value: d, label: d === 'all' ? 'All destinations' : d }))} />
            <Select label="Duration" value={durationFilter} onChange={setDurationFilter} options={[{ value: 'any', label: 'Any duration' }, { value: 'half', label: 'Half day' }, { value: 'day', label: '1 day' }, { value: 'multi', label: '2–3 days' }, { value: 'long', label: '4+ days' }]} />
            <Select label="Price" value={priceRange} onChange={setPriceRange} options={[{ value: 'any', label: 'Any price' }, { value: '<200', label: 'Under RM 200' }, { value: '200-500', label: 'RM 200–500' }, { value: '500-1500', label: 'RM 500–1,500' }, { value: '1500+', label: 'RM 1,500+' }]} />
            <Select label="Sort by" value={sort} onChange={setSort} options={[{ value: 'featured', label: 'Featured' }, { value: 'price-asc', label: 'Price (low to high)' }, { value: 'price-desc', label: 'Price (high to low)' }, { value: 'rating', label: 'Highest rated' }]} />
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, fontSize: 14, color: '#5a5544' }}>
          <div>Showing <strong>{(page - 1) * perPage + 1}–{Math.min(page * perPage, sorted.length)}</strong> of {sorted.length} packages</div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 20 }}>
          {paged.map(p => <TourCard key={p.id} pkg={p} onClick={() => navigate({ route: 'tour', slug: p.slug })} />)}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div style={{ marginTop: 40, display: 'flex', gap: 8, justifyContent: 'center' }}>
            <button onClick={() => setPage(Math.max(1, page - 1))} disabled={page === 1} style={{ padding: '8px 14px', borderRadius: 10, border: '1px solid #e2dccb', background: 'white', opacity: page === 1 ? 0.4 : 1 }}>← Prev</button>
            {[...Array(totalPages)].map((_, i) => (
              <button key={i} onClick={() => setPage(i + 1)} style={{ width: 40, height: 40, borderRadius: 10, border: page === i + 1 ? '1px solid var(--accent)' : '1px solid #e2dccb', background: page === i + 1 ? 'var(--accent)' : 'white', color: page === i + 1 ? 'white' : 'var(--ink)', fontWeight: 500 }}>{i + 1}</button>
            ))}
            <button onClick={() => setPage(Math.min(totalPages, page + 1))} disabled={page === totalPages} style={{ padding: '8px 14px', borderRadius: 10, border: '1px solid #e2dccb', background: 'white', opacity: page === totalPages ? 0.4 : 1 }}>Next →</button>
          </div>
        )}
      </div>

      <PublicFooter state={state} navigate={navigate} />
    </div>
  );
};

// -------- TOUR DETAIL --------
const PublicTour = ({ state, navigate, slug }) => {
  const pkg = state.packages.find(p => p.slug === slug);
  const [galleryIdx, setGalleryIdx] = useState(0);
  const [openDay, setOpenDay] = useState(0);

  if (!pkg) return <div style={{ padding: 60, textAlign: 'center' }}>Package not found. <Btn onClick={() => navigate({ route: 'tours' })}>Back to tours</Btn></div>;

  const related = state.packages.filter(p => p.id !== pkg.id && p.status === 'published' && p.category === pkg.category).slice(0, 3);

  return (
    <div style={{ background: 'var(--paper)' }}>
      <div style={{ background: 'var(--green-deep)', padding: '28px 32px 0' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <PublicNav state={state} navigate={navigate} dark />
        </div>
      </div>

      {/* Gallery */}
      <section style={{ background: 'var(--green-deep)', padding: '24px 32px 48px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <button onClick={() => navigate({ route: 'tours' })} style={{ color: '#F5EEDE', fontSize: 13, opacity: 0.8, marginBottom: 16, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <Icon name="arrow-left" size={14} /> All packages
          </button>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gridTemplateRows: 'repeat(2, 200px)', gap: 8, borderRadius: 20, overflow: 'hidden' }}>
            <div style={{ gridColumn: 'span 2', gridRow: 'span 2' }}>
              <Img src={pkg.gallery[galleryIdx] || pkg.hero} style={{ width: '100%', height: '100%' }} />
            </div>
            {(pkg.gallery.slice(0, 4).length > 1 ? pkg.gallery.slice(0, 4) : [pkg.hero, pkg.hero, pkg.hero, pkg.hero]).map((g, i) => (
              <div key={i} onClick={() => setGalleryIdx(i)} style={{ cursor: 'pointer', position: 'relative' }}>
                <Img src={g} style={{ width: '100%', height: '100%' }} />
                {i === 3 && <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)', color: 'white', display: 'grid', placeItems: 'center', fontSize: 14, fontWeight: 500 }}>+{pkg.gallery.length - 4} more</div>}
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Main content */}
      <section style={{ padding: '48px 32px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', display: 'grid', gridTemplateColumns: '1fr 380px', gap: 48 }}>
          <div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
              <Pill tone="green">{pkg.category === 'inbound' ? 'Sarawak' : 'Outbound'}</Pill>
              {pkg.tags.map(t => <Pill key={t} tone="neutral">{t}</Pill>)}
            </div>
            <h1 style={{ fontSize: 54, lineHeight: 1.05, letterSpacing: '-0.025em', fontWeight: 300 }}>{pkg.title}</h1>
            <div style={{ display: 'flex', gap: 24, marginTop: 16, flexWrap: 'wrap', color: '#5a5544', fontSize: 14 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="map-pin" size={14} />{pkg.destination}</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="clock" size={14} />{pkg.duration}</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="star" size={14} style={{ color: 'var(--accent)' }} />{pkg.rating} ({pkg.reviews} reviews)</span>
            </div>

            <p style={{ fontFamily: 'Fraunces', fontSize: 22, lineHeight: 1.45, marginTop: 32, fontWeight: 300, letterSpacing: '-0.01em' }}>{pkg.short}</p>
            <p style={{ fontSize: 15, lineHeight: 1.65, marginTop: 20, color: '#3a3a33' }}>{pkg.description}</p>

            {/* Itinerary */}
            <div style={{ marginTop: 56 }}>
              <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--accent)', marginBottom: 8 }}>Day by day</div>
              <h2 style={{ fontSize: 34, letterSpacing: '-0.02em', marginBottom: 20 }}>Itinerary</h2>
              <div style={{ borderTop: '1px solid #e2dccb' }}>
                {pkg.itinerary.map((d, i) => (
                  <div key={i} style={{ borderBottom: '1px solid #e2dccb' }}>
                    <button onClick={() => setOpenDay(openDay === i ? -1 : i)} style={{ width: '100%', padding: '20px 0', display: 'flex', alignItems: 'center', gap: 20, textAlign: 'left' }}>
                      <div style={{ fontFamily: 'Geist Mono', fontSize: 13, color: 'var(--accent)', width: 60 }}>Day {d.day}</div>
                      <div style={{ flex: 1, fontFamily: 'Fraunces', fontSize: 22, letterSpacing: '-0.015em' }}>{d.title}</div>
                      <Icon name={openDay === i ? 'chevron-up' : 'chevron-down'} size={18} />
                    </button>
                    {openDay === i && (
                      <div style={{ paddingLeft: 80, paddingBottom: 24, fontSize: 15, lineHeight: 1.65, color: '#3a3a33', maxWidth: 720 }}>
                        {d.text}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>

            {/* Pricing */}
            {pkg.pricing.length > 0 && (
              <div style={{ marginTop: 56 }}>
                <h2 style={{ fontSize: 34, letterSpacing: '-0.02em', marginBottom: 20 }}>Pricing</h2>
                <div style={{ background: 'white', borderRadius: 14, border: '1px solid #e8e1cf', overflow: 'hidden' }}>
                  {pkg.pricing.map((p, i) => (
                    <div key={i} style={{ padding: '18px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: i < pkg.pricing.length - 1 ? '1px solid #eee7d6' : 0 }}>
                      <div style={{ fontSize: 15 }}>{p.label}</div>
                      <div style={{ fontFamily: 'Fraunces', fontSize: 22, letterSpacing: '-0.02em' }}>{fmtMYR(p.price)}<span style={{ fontSize: 13, color: '#8a8573', fontFamily: 'Geist', marginLeft: 4 }}>/pax</span></div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* In/Ex */}
            <div style={{ marginTop: 56, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
              <div>
                <h3 style={{ fontSize: 22, marginBottom: 16, letterSpacing: '-0.015em' }}>What's included</h3>
                <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 10 }}>
                  {pkg.inclusions.map((t, i) => <li key={i} style={{ display: 'flex', gap: 10, fontSize: 14 }}><Icon name="check" size={16} style={{ color: 'var(--green)', flexShrink: 0, marginTop: 3 }} />{t}</li>)}
                </ul>
              </div>
              <div>
                <h3 style={{ fontSize: 22, marginBottom: 16, letterSpacing: '-0.015em' }}>Not included</h3>
                <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 10 }}>
                  {pkg.exclusions.map((t, i) => <li key={i} style={{ display: 'flex', gap: 10, fontSize: 14 }}><Icon name="x" size={16} style={{ color: '#c9826c', flexShrink: 0, marginTop: 3 }} />{t}</li>)}
                </ul>
              </div>
            </div>
          </div>

          {/* Sticky sidebar */}
          <aside>
            <div style={{ position: 'sticky', top: 24, background: 'white', borderRadius: 18, border: '1px solid #e8e1cf', padding: 28, boxShadow: '0 10px 30px rgba(0,0,0,0.06)' }}>
              <div style={{ fontSize: 12, color: '#8a8573', textTransform: 'uppercase', letterSpacing: '0.08em' }}>From</div>
              <div style={{ fontFamily: 'Fraunces', fontSize: 42, letterSpacing: '-0.025em', lineHeight: 1 }}>{fmtMYR(pkg.priceFrom)}<span style={{ fontSize: 15, color: '#8a8573', fontFamily: 'Geist', marginLeft: 4 }}>/pax</span></div>
              <div style={{ marginTop: 20, display: 'grid', gap: 10 }}>
                <Btn kind="primary" size="lg" icon="mail" full onClick={() => navigate({ route: 'contact', prefillPkg: pkg.title })}>Inquire now</Btn>
                <Btn kind="dark" size="lg" icon="message-circle" full onClick={() => window.open(`https://wa.me/${state.settings.whatsapp.replace(/[^\d]/g, '')}?text=${encodeURIComponent('Hi! I\'m interested in the ' + pkg.title + ' package.')}`, '_blank')}>WhatsApp us</Btn>
              </div>
              <div style={{ marginTop: 24, paddingTop: 24, borderTop: '1px solid #eee7d6', display: 'grid', gap: 12, fontSize: 13, color: '#5a5544' }}>
                <div style={{ display: 'flex', gap: 10 }}><Icon name="check" size={14} style={{ color: 'var(--green)' }} />Free cancellation up to 7 days</div>
                <div style={{ display: 'flex', gap: 10 }}><Icon name="check" size={14} style={{ color: 'var(--green)' }} />Instant confirmation</div>
                <div style={{ display: 'flex', gap: 10 }}><Icon name="check" size={14} style={{ color: 'var(--green)' }} />Bank transfer or FPX</div>
              </div>
            </div>
          </aside>
        </div>
      </section>

      {/* Related */}
      {related.length > 0 && (
        <section style={{ background: 'var(--cream)', padding: '72px 32px' }}>
          <div style={{ maxWidth: 1280, margin: '0 auto' }}>
            <h2 style={{ fontSize: 38, letterSpacing: '-0.02em', marginBottom: 28 }}>You might also like</h2>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 20 }}>
              {related.map(r => <TourCard key={r.id} pkg={r} onClick={() => { navigate({ route: 'tour', slug: r.slug }); window.scrollTo(0, 0); }} />)}
            </div>
          </div>
        </section>
      )}

      <PublicFooter state={state} navigate={navigate} />
    </div>
  );
};

// -------- VEHICLES --------
const PublicVehicles = ({ state, navigate }) => {
  const [typeFilter, setTypeFilter] = useState('all');
  const [capFilter, setCapFilter] = useState('any');
  const list = state.vehicles.filter(v => v.status === 'published')
    .filter(v => typeFilter === 'all' || v.type === typeFilter)
    .filter(v => capFilter === 'any' || (capFilter === '4' && v.capacity <= 4) || (capFilter === '7' && v.capacity > 4 && v.capacity <= 7) || (capFilter === '15' && v.capacity > 7 && v.capacity <= 15) || (capFilter === 'bus' && v.capacity > 15));

  return (
    <div style={{ background: 'var(--paper)' }}>
      <div style={{ background: 'var(--green-deep)', color: '#F5EEDE', padding: '28px 32px 64px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <PublicNav state={state} navigate={navigate} dark />
          <div style={{ marginTop: 48 }}>
            <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.12em', color: '#E85D2F' }}>Car rental · Chauffeured transport</div>
            <h1 style={{ fontSize: 64, letterSpacing: '-0.03em', marginTop: 8, fontWeight: 300 }}>Move around. <span style={{ fontStyle: 'italic' }}>Kuching-wide.</span></h1>
            <p style={{ fontSize: 16, marginTop: 12, maxWidth: 640, color: 'rgba(245,238,222,0.75)' }}>Self-drive economy to executive MPV to 4WD for the interior. All vehicles insured, serviced monthly.</p>
          </div>
        </div>
      </div>

      <div style={{ maxWidth: 1280, margin: '-32px auto 0', padding: '0 32px 80px' }}>
        <div style={{ background: 'white', borderRadius: 20, padding: 20, boxShadow: '0 10px 30px rgba(0,0,0,0.06)', border: '1px solid #e8e1cf', marginBottom: 32, display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
          <span style={{ fontSize: 13, color: '#8a8573', marginRight: 8 }}>Filter:</span>
          {['all', 'Sedan', 'SUV', 'MPV', 'Van', 'Bus', '4WD'].map(t => (
            <button key={t} onClick={() => setTypeFilter(t)} style={{ padding: '8px 14px', borderRadius: 999, fontSize: 13, fontWeight: 500, background: typeFilter === t ? 'var(--ink)' : 'transparent', color: typeFilter === t ? 'white' : 'var(--ink)', border: '1px solid ' + (typeFilter === t ? 'var(--ink)' : '#e2dccb') }}>
              {t === 'all' ? 'All types' : t}
            </button>
          ))}
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center' }}>
            <span style={{ fontSize: 13, color: '#8a8573' }}>Capacity:</span>
            <Select value={capFilter} onChange={setCapFilter} options={[{ value: 'any', label: 'Any' }, { value: '4', label: 'Up to 4' }, { value: '7', label: '5–7' }, { value: '15', label: '8–15' }, { value: 'bus', label: '16+' }]} style={{ width: 140 }} />
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 20 }}>
          {list.map(v => (
            <div key={v.id} style={{ background: 'white', borderRadius: 16, overflow: 'hidden', border: '1px solid #e8e1cf', display: 'flex', flexDirection: 'column' }}>
              <div style={{ position: 'relative' }}>
                <Img src={v.photo} ratio="16 / 10" />
                <div style={{ position: 'absolute', top: 12, left: 12 }}>
                  <Pill tone={v.available ? 'green' : 'red'}>{v.available ? 'Available' : 'Booked out'}</Pill>
                </div>
                <div style={{ position: 'absolute', top: 12, right: 12 }}>
                  <Pill tone="white">{v.type}</Pill>
                </div>
              </div>
              <div style={{ padding: 22, flex: 1, display: 'flex', flexDirection: 'column' }}>
                <h3 style={{ fontSize: 22, letterSpacing: '-0.015em', lineHeight: 1.2 }}>{v.name}</h3>
                <p style={{ fontSize: 13, color: '#5a5544', marginTop: 6, lineHeight: 1.5 }}>{v.description}</p>
                <div style={{ display: 'flex', gap: 14, marginTop: 14, fontSize: 13, color: '#5a5544' }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="users" size={13} />{v.capacity} pax</span>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="briefcase" size={13} />{v.luggage} bags</span>
                </div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 14 }}>
                  {v.features.slice(0, 3).map(f => <span key={f} style={{ fontSize: 12, padding: '3px 8px', background: '#EFEADA', borderRadius: 6, color: '#5a5544' }}>{f}</span>)}
                </div>
                <div style={{ marginTop: 'auto', paddingTop: 18, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: 11, color: '#8a8573', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Daily rate</div>
                    <div style={{ fontFamily: 'Fraunces', fontSize: 22, letterSpacing: '-0.02em' }}>{fmtMYR(v.rate)}<span style={{ fontSize: 12, color: '#8a8573', fontFamily: 'Geist', marginLeft: 4 }}>/day</span></div>
                  </div>
                  <Btn kind="primary" size="sm" disabled={!v.available} onClick={() => navigate({ route: 'contact', prefillPkg: v.name + ' rental', prefillSvc: 'Car Rental' })}>Inquire</Btn>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <PublicFooter state={state} navigate={navigate} />
    </div>
  );
};

// -------- BLOG LISTING --------
const PublicBlog = ({ state, navigate }) => {
  const posts = state.blogs.filter(b => b.status === 'published');
  const [hero, ...rest] = posts;
  return (
    <div style={{ background: 'var(--paper)' }}>
      <div style={{ background: 'var(--green-deep)', padding: '28px 32px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}><PublicNav state={state} navigate={navigate} dark /></div>
      </div>

      <section style={{ padding: '60px 32px', maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--accent)' }}>Journal</div>
        <h1 style={{ fontSize: 64, letterSpacing: '-0.03em', marginTop: 8, fontWeight: 300 }}>Field <span style={{ fontStyle: 'italic' }}>notes.</span></h1>

        {/* Hero post */}
        {hero && (
          <div onClick={() => navigate({ route: 'blogpost', slug: hero.slug })} style={{ marginTop: 40, cursor: 'pointer', display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 40, alignItems: 'center' }}>
            <Img src={hero.featuredImage} ratio="16 / 10" style={{ borderRadius: 18 }} />
            <div>
              <Pill tone="orange">{hero.category}</Pill>
              <h2 style={{ fontSize: 42, letterSpacing: '-0.025em', marginTop: 16, lineHeight: 1.1 }}>{hero.title}</h2>
              <p style={{ fontSize: 16, color: '#5a5544', marginTop: 14, lineHeight: 1.6 }}>{hero.excerpt}</p>
              <div style={{ marginTop: 20, fontSize: 13, color: '#8a8573' }}>{hero.author} · {fmtDate(hero.date)} · 6 min read</div>
            </div>
          </div>
        )}

        {/* Grid */}
        <div style={{ marginTop: 64, display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 28 }}>
          {rest.map(b => (
            <div key={b.id} onClick={() => navigate({ route: 'blogpost', slug: b.slug })} style={{ cursor: 'pointer' }}>
              <div style={{ borderRadius: 14, overflow: 'hidden', marginBottom: 14 }}>
                <Img src={b.featuredImage} ratio="16 / 10" />
              </div>
              <Pill tone="orange">{b.category}</Pill>
              <h3 style={{ fontSize: 24, letterSpacing: '-0.015em', marginTop: 10, lineHeight: 1.2 }}>{b.title}</h3>
              <p style={{ fontSize: 14, color: '#5a5544', marginTop: 8, lineHeight: 1.55 }}>{b.excerpt}</p>
              <div style={{ fontSize: 12, color: '#8a8573', marginTop: 10 }}>{b.author} · {fmtDate(b.date)}</div>
            </div>
          ))}
        </div>
      </section>

      <PublicFooter state={state} navigate={navigate} />
    </div>
  );
};

// -------- BLOG DETAIL --------
const PublicBlogPost = ({ state, navigate, slug }) => {
  const post = state.blogs.find(b => b.slug === slug);
  if (!post) return <div style={{ padding: 60, textAlign: 'center' }}>Post not found.</div>;
  return (
    <div style={{ background: 'var(--paper)' }}>
      <div style={{ background: 'var(--green-deep)', padding: '28px 32px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}><PublicNav state={state} navigate={navigate} dark /></div>
      </div>

      <article style={{ maxWidth: 800, margin: '0 auto', padding: '48px 32px' }}>
        <button onClick={() => navigate({ route: 'blog' })} style={{ fontSize: 13, color: '#5a5544', display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 28 }}>
          <Icon name="arrow-left" size={14} /> All articles
        </button>
        <Pill tone="orange">{post.category}</Pill>
        <h1 style={{ fontSize: 56, lineHeight: 1.05, letterSpacing: '-0.03em', marginTop: 20, fontWeight: 300 }}>{post.title}</h1>
        <div style={{ marginTop: 20, display: 'flex', gap: 20, fontSize: 14, color: '#5a5544' }}>
          <span>By {post.author}</span>
          <span>·</span>
          <span>{fmtDate(post.date)}</span>
          <span>·</span>
          <span>6 min read</span>
        </div>
        <div style={{ marginTop: 36, borderRadius: 16, overflow: 'hidden' }}>
          <Img src={post.featuredImage} ratio="16 / 9" />
        </div>
        <div style={{ marginTop: 40, fontFamily: 'Fraunces', fontSize: 22, lineHeight: 1.5, letterSpacing: '-0.005em', fontWeight: 300 }}>
          {post.excerpt}
        </div>
        <div style={{ marginTop: 32, fontSize: 17, lineHeight: 1.75, color: '#2a2f28' }}>
          {post.body}
        </div>
        <div style={{ marginTop: 48, padding: '32px 0', borderTop: '1px solid #e8e1cf', borderBottom: '1px solid #e8e1cf', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
          <div style={{ fontSize: 14, color: '#5a5544' }}>Enjoyed this? Share with a friend.</div>
          <div style={{ display: 'flex', gap: 8 }}>
            {['facebook', 'twitter', 'mail', 'link'].map(s => (
              <button key={s} style={{ width: 38, height: 38, borderRadius: '50%', border: '1px solid #e2dccb', display: 'grid', placeItems: 'center' }}>
                <Icon name={s} size={14} />
              </button>
            ))}
          </div>
        </div>
      </article>

      <PublicFooter state={state} navigate={navigate} />
    </div>
  );
};

// -------- DYNAMIC PAGE --------
const PublicPage = ({ state, navigate, slug }) => {
  const page = state.pages.find(p => p.slug === slug);
  if (!page) return <div style={{ padding: 60, textAlign: 'center' }}>Page not found.</div>;
  return (
    <div style={{ background: 'var(--paper)' }}>
      <div style={{ background: 'var(--green-deep)', padding: '28px 32px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}><PublicNav state={state} navigate={navigate} dark /></div>
      </div>
      <article style={{ maxWidth: 760, margin: '0 auto', padding: '60px 32px' }}>
        <h1 style={{ fontSize: 64, letterSpacing: '-0.03em', lineHeight: 1.05, fontWeight: 300 }}>{page.title}</h1>
        <div style={{ fontSize: 13, color: '#8a8573', marginTop: 16 }}>Last updated {fmtDate(page.updated)}</div>
        <div style={{ marginTop: 40, fontSize: 16, lineHeight: 1.75, color: '#2a2f28', whiteSpace: 'pre-wrap' }}>{page.body}</div>
      </article>
      <PublicFooter state={state} navigate={navigate} />
    </div>
  );
};

// -------- CONTACT / INQUIRY --------
const PublicContact = ({ state, navigate, setState, nav }) => {
  const [form, setForm] = useState({
    name: '', email: '', phone: '',
    service: nav.prefillSvc || 'Tour',
    date: '',
    package: nav.prefillPkg || '',
    message: '',
  });
  const [step, setStep] = useState('form'); // form -> review -> sent
  const [errors, setErrors] = useState({});
  const { show, node } = useToast();

  const validate = () => {
    const e = {};
    if (!form.name) e.name = 'Required';
    if (!form.email || !/.+@.+\..+/.test(form.email)) e.email = 'Valid email required';
    if (!form.phone) e.phone = 'Required';
    if (!form.message || form.message.length < 10) e.message = 'Please share a bit more (10+ chars)';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const onReview = () => { if (validate()) setStep('review'); };

  const onSubmit = () => {
    const newInquiry = {
      id: 'i' + String(Date.now()).slice(-6),
      ...form,
      preferred: form.date,
      status: 'new',
    };
    setState(s => ({ ...s, inquiries: [newInquiry, ...s.inquiries] }));
    setStep('sent');
  };

  const waMessage = () => {
    const lines = [
      `Hi ${state.settings.agencyName}, I'd like to inquire about:`,
      `• Name: ${form.name}`,
      `• Email: ${form.email}`,
      `• Phone: ${form.phone}`,
      `• Service: ${form.service}`,
      form.package ? `• Package/Vehicle: ${form.package}` : null,
      form.date ? `• Preferred date: ${form.date}` : null,
      `• Message: ${form.message}`,
    ].filter(Boolean).join('\n');
    return encodeURIComponent(lines);
  };

  return (
    <div style={{ background: 'var(--paper)' }}>
      <div style={{ background: 'var(--green-deep)', padding: '28px 32px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}><PublicNav state={state} navigate={navigate} dark /></div>
      </div>

      <section style={{ padding: '60px 32px', maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 60 }}>
          <div>
            <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--accent)' }}>Inquire</div>
            <h1 style={{ fontSize: 54, letterSpacing: '-0.03em', marginTop: 8, fontWeight: 300, lineHeight: 1.05 }}>Tell us <span style={{ fontStyle: 'italic' }}>what you're after.</span></h1>
            <p style={{ fontSize: 16, color: '#5a5544', marginTop: 14, lineHeight: 1.6, maxWidth: 520 }}>
              Fill this in and we'll send it straight to our inbox + your WhatsApp. A real human replies within 4 working hours.
            </p>

            <div style={{ marginTop: 36 }}>
              {step === 'form' && (
                <div style={{ background: 'white', borderRadius: 18, padding: 32, border: '1px solid #e8e1cf', display: 'grid', gap: 16 }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                    <Input label="Your name" value={form.name} onChange={v => setForm({ ...form, name: v })} required hint={errors.name} />
                    <Input label="Phone" value={form.phone} onChange={v => setForm({ ...form, phone: v })} placeholder="+60 12 ..." required hint={errors.phone} />
                  </div>
                  <Input label="Email" type="email" value={form.email} onChange={v => setForm({ ...form, email: v })} required hint={errors.email} />
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                    <Select label="Service type" value={form.service} onChange={v => setForm({ ...form, service: v })} options={['Tour', 'Car Rental', 'Hotel', 'Ticketing', 'General']} required />
                    <Input label="Preferred date" type="date" value={form.date} onChange={v => setForm({ ...form, date: v })} />
                  </div>
                  <Input label="Package / vehicle (optional)" value={form.package} onChange={v => setForm({ ...form, package: v })} placeholder="e.g. Mulu Caves 3D2N" />
                  <Textarea label="Tell us more" value={form.message} onChange={v => setForm({ ...form, message: v })} rows={5} placeholder="Group size, budget, preferences, anything useful..." required hint={errors.message} />
                  <div style={{ marginTop: 8, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                    <Btn kind="primary" size="lg" icon="arrow-right" onClick={onReview}>Review inquiry</Btn>
                    <Btn kind="ghost" size="lg" onClick={() => setForm({ name: '', email: '', phone: '', service: 'Tour', date: '', package: '', message: '' })}>Clear</Btn>
                  </div>
                </div>
              )}

              {step === 'review' && (
                <div style={{ background: 'white', borderRadius: 18, padding: 32, border: '1px solid #e8e1cf' }}>
                  <div style={{ fontFamily: 'Fraunces', fontSize: 28, letterSpacing: '-0.02em' }}>Quick check — does this look right?</div>
                  <div style={{ marginTop: 20, display: 'grid', gap: 10 }}>
                    {[
                      ['Name', form.name],
                      ['Email', form.email],
                      ['Phone', form.phone],
                      ['Service', form.service],
                      ['Package', form.package || '—'],
                      ['Preferred date', form.date || '—'],
                    ].map(([k, v]) => (
                      <div key={k} style={{ display: 'grid', gridTemplateColumns: '140px 1fr', padding: '10px 0', borderBottom: '1px dashed #eee7d6' }}>
                        <div style={{ fontSize: 13, color: '#8a8573' }}>{k}</div>
                        <div style={{ fontSize: 14 }}>{v}</div>
                      </div>
                    ))}
                    <div style={{ padding: '10px 0' }}>
                      <div style={{ fontSize: 13, color: '#8a8573' }}>Message</div>
                      <div style={{ fontSize: 14, marginTop: 6, whiteSpace: 'pre-wrap', lineHeight: 1.55 }}>{form.message}</div>
                    </div>
                  </div>
                  <div style={{ marginTop: 24, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                    <Btn kind="primary" size="lg" icon="message-circle" onClick={() => { onSubmit(); window.open(`https://wa.me/${state.settings.whatsapp.replace(/[^\d]/g, '')}?text=${waMessage()}`, '_blank'); }}>Send via WhatsApp</Btn>
                    <Btn kind="dark" size="lg" icon="mail" onClick={onSubmit}>Email only</Btn>
                    <Btn kind="ghost" size="lg" onClick={() => setStep('form')}>Edit</Btn>
                  </div>
                </div>
              )}

              {step === 'sent' && (
                <div style={{ background: 'white', borderRadius: 18, padding: 48, border: '1px solid #e8e1cf', textAlign: 'center' }}>
                  <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(46,92,66,0.12)', display: 'grid', placeItems: 'center', margin: '0 auto 20px' }}>
                    <Icon name="check" size={28} style={{ color: 'var(--green)' }} />
                  </div>
                  <h2 style={{ fontSize: 32, letterSpacing: '-0.02em' }}>Sent. <span style={{ fontStyle: 'italic' }}>We've got it.</span></h2>
                  <p style={{ fontSize: 15, color: '#5a5544', marginTop: 12, maxWidth: 460, margin: '12px auto 0', lineHeight: 1.55 }}>A confirmation is on its way to {form.email}. Our team usually replies within 4 working hours.</p>
                  <div style={{ marginTop: 24, display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
                    <Btn kind="primary" onClick={() => navigate({ route: 'home' })}>Back to home</Btn>
                    <Btn kind="ghost" onClick={() => { setForm({ name: '', email: '', phone: '', service: 'Tour', date: '', package: '', message: '' }); setStep('form'); }}>Submit another</Btn>
                  </div>
                </div>
              )}
            </div>
          </div>

          <aside>
            <div style={{ background: 'var(--green-deep)', color: '#F5EEDE', borderRadius: 18, padding: 32 }}>
              <h3 style={{ fontFamily: 'Fraunces', fontSize: 26, letterSpacing: '-0.015em' }}>Office & contact</h3>
              <div style={{ marginTop: 20, display: 'grid', gap: 16, fontSize: 14 }}>
                <div><Icon name="map-pin" size={14} style={{ marginRight: 8 }} />{state.settings.address}</div>
                <div><Icon name="phone" size={14} style={{ marginRight: 8 }} />{state.settings.phone}</div>
                <div><Icon name="message-circle" size={14} style={{ marginRight: 8 }} />{state.settings.whatsapp}</div>
                <div><Icon name="mail" size={14} style={{ marginRight: 8 }} />{state.settings.email}</div>
                <div><Icon name="clock" size={14} style={{ marginRight: 8 }} />{state.settings.hours}</div>
              </div>
            </div>

            <div style={{ marginTop: 20, background: 'white', borderRadius: 18, overflow: 'hidden', border: '1px solid #e8e1cf' }}>
              <div style={{ position: 'relative', height: 240, background: 'linear-gradient(135deg, #c4d9c7, #a9c0ae)' }}>
                <div style={{ position: 'absolute', inset: 0, background: 'repeating-linear-gradient(45deg, transparent, transparent 14px, rgba(255,255,255,0.3) 14px, rgba(255,255,255,0.3) 15px)' }} />
                <div style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)', textAlign: 'center' }}>
                  <Icon name="map-pin" size={32} style={{ color: 'var(--accent)' }} />
                  <div style={{ fontFamily: 'Geist Mono', fontSize: 12, marginTop: 8, color: 'var(--ink)' }}>KUCHING · 1.5533°N 110.3592°E</div>
                </div>
              </div>
              <div style={{ padding: 20, fontSize: 13, color: '#5a5544' }}>Wisma Satok, 3rd floor — above the Starbucks, opposite the Satok mosque.</div>
            </div>
          </aside>
        </div>
      </section>

      <PublicFooter state={state} navigate={navigate} />
      {node}
    </div>
  );
};

Object.assign(window, { PublicTours, PublicTour, PublicVehicles, PublicBlog, PublicBlogPost, PublicPage, PublicContact });
