/* home.jsx — Fraser Finds hub home page */

const ALL_CATS = {
  calendar:   { key:'calendar',   label:'Events Calendar',  blurb:'What\'s on in Prince George this week.',      Icon:IconCalendar, tint:'#cf9521' },
  foodtrucks: { key:'foodtrucks', label:'Food Trucks',       blurb:'Who\'s out and where — updated weekly.',      Icon:IconTruck,    tint:'#b3603f' },
  farmstands: { key:'farmstands', label:'Local Markets & Stands', blurb:'Farm stands, markets, and seasonal local produce.', Icon:IconSprout, tint:'#5c7461' },
  garage:     { key:'garage',     label:'Garage Sale Map',   blurb:'Find the trail of driveways this weekend.',  Icon:IconTag,      tint:'#9a3b4f', href:'/garagesales.html' },
};

// May (4) – Sept (8) = garage sale season: garage first
// Oct–Apr: calendar first, garage last
function getOrderedCats() {
  const month = new Date().getMonth(); // 0-indexed
  const garageSeason = month >= 4 && month <= 8;
  return garageSeason
    ? [ALL_CATS.garage,     ALL_CATS.calendar, ALL_CATS.farmstands, ALL_CATS.foodtrucks]
    : [ALL_CATS.calendar,   ALL_CATS.farmstands, ALL_CATS.foodtrucks, ALL_CATS.garage];
}

const CATS = getOrderedCats();

function CatCard({ c, big }) {
  const { go } = useFF();
  const handleClick = () => {
    if (c.href) { window.location.href = c.href; return; }
    go(c.key);
  };
  return (
    <button onClick={handleClick} className="card cat-card"
      style={{ textAlign:'left', padding: big?'26px':'20px', display:'flex', flexDirection:'column', gap: big?14:10,
        cursor:'pointer', transition:'transform .15s, box-shadow .15s', minHeight: big?200:0, border:'none', width:'100%' }}>
      <span style={{ width:54, height:54, borderRadius:15, background:`${c.tint}1f`, color:c.tint, display:'grid', placeItems:'center' }}>
        <c.Icon size={28}/>
      </span>
      <div style={{ marginTop:'auto' }}>
        <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize: big?22:18, letterSpacing:'-.01em' }}>{c.label}</div>
        <div style={{ color:'var(--ink-soft)', fontSize:14.5, marginTop:4 }}>{c.blurb}</div>
      </div>
      <span style={{ display:'inline-flex', alignItems:'center', gap:6, color:c.tint, fontWeight:600, fontSize:13.5 }}>
        Open <IconArrow size={16}/>
      </span>
    </button>
  );
}

function PulpStrip() {
  return (
    <a href="/pulp" style={{ display:'flex', alignItems:'center', gap:22, flexWrap:'wrap',
        marginTop:18, padding:'24px 28px', textDecoration:'none', color:'var(--ink)',
        border:'2px solid var(--ink)', borderRadius:'var(--radius-lg)', background:'var(--paper)' }}>
      <span style={{ width:54, height:54, flexShrink:0, borderRadius:15, background:'#9a3b4f1f', color:'#9a3b4f', display:'grid', placeItems:'center' }}>
        <IconNews size={28}/>
      </span>
      <div style={{ flex:1, minWidth:220 }}>
        <div style={{ fontFamily:'var(--serif)', fontWeight:900, fontSize:24, letterSpacing:'-.01em', lineHeight:1.1 }}>
          The Pulp &amp; <em style={{ color:'#9a3b4f' }}>Circumstance</em>
        </div>
        <div style={{ color:'var(--ink-soft)', fontSize:14.5, marginTop:4, fontFamily:'var(--serif)', fontStyle:'italic' }}>
          Prince George's most trusted source for news we entirely made up.
        </div>
      </div>
      <span style={{ display:'inline-flex', alignItems:'center', gap:6, color:'#9a3b4f', fontWeight:600, fontSize:13.5 }}>
        Read the latest edition <IconArrow size={16}/>
      </span>
    </a>
  );
}

function EventStrip() {
  const { go } = useFF();
  const [events, setEvents] = React.useState([]);

  React.useEffect(() => {
    fetch('/api/events')
      .then(r => r.ok ? r.json() : [])
      .then(data => { if (Array.isArray(data)) setEvents(data.slice(0, 4)); })
      .catch(() => {});
  }, []);

  if (events.length === 0) return null;

  return (
    <div>
      <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:16 }}>
        <h2 style={{ fontSize:26 }}>This week in town</h2>
        <button onClick={()=>go('calendar')} style={{ background:'none', border:'none', color:'var(--accent)', fontWeight:600, fontSize:14.5, display:'inline-flex', gap:6, alignItems:'center' }}>
          Full calendar <IconArrow size={16}/>
        </button>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        {events.map((e, i) => {
          const d = e.date ? new Date(e.date + 'T12:00:00') : null;
          const dayNum = d && !isNaN(d) ? d.getDate() : '';
          const mon = d && !isNaN(d) ? d.toLocaleDateString('en-CA', { month:'short' }).toUpperCase() : '';
          return (
            <button key={e.id||i} onClick={()=>go('calendar')} className="card"
              style={{ display:'flex', alignItems:'center', gap:16, padding:'13px 16px', textAlign:'left', cursor:'pointer', border:'none', width:'100%' }}>
              <div style={{ textAlign:'center', flexShrink:0, width:52 }}>
                <div style={{ fontFamily:'var(--display)', fontWeight:800, fontSize:24, lineHeight:1, color:'var(--accent)' }}>{dayNum}</div>
                <div style={{ fontSize:11, fontWeight:700, letterSpacing:'.1em', color:'var(--ink-faint)' }}>{mon}</div>
              </div>
              <div style={{ width:1.5, alignSelf:'stretch', background:'var(--line)' }}/>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontWeight:700, fontSize:16 }}>{e.title}</div>
                <div style={{ color:'var(--ink-soft)', fontSize:13.5, display:'flex', gap:12, marginTop:2, flexWrap:'wrap' }}>
                  {e.start && <span style={{ display:'inline-flex', gap:5, alignItems:'center' }}><IconClock size={14}/>{e.start}</span>}
                  {e.venue && <span style={{ display:'inline-flex', gap:5, alignItems:'center' }}><IconPin size={14}/>{e.venue}</span>}
                </div>
              </div>
              {e.category && <span className="chip" style={{ flexShrink:0 }}>{e.category}</span>}
            </button>
          );
        })}
      </div>
    </div>
  );
}


/* ============ ALMANAC LAYOUT (default) ============ */
function HomeAlmanac() {
  const { go } = useFF();
  const today = new Date();
  const dateStr = today.toLocaleDateString('en-CA', { weekday:'long', month:'long', day:'numeric', year:'numeric' });
  return (
    <div>
      <div style={{ borderBottom:'2.5px solid var(--ink)', background:'var(--paper)' }}>
        <div className="page-wrap" style={{ paddingTop:18 }}>
          <div style={{ display:'flex', justifyContent:'space-between', fontSize:12, fontWeight:700, letterSpacing:'.14em', textTransform:'uppercase', color:'var(--ink-faint)', borderBottom:'1.5px solid var(--line)', paddingBottom:10 }}>
            <span>{dateStr}</span>
            <span className="ff-mast-side">Prince George, B.C.</span>
          </div>
          <div style={{ textAlign:'center', padding:'30px 0 22px' }}>
            <div className="eyebrow" style={{ justifyContent:'center', marginBottom:14 }}>The neighbourly guide to Prince George</div>
            <h1 style={{ fontSize:'clamp(46px,8vw,104px)', letterSpacing:'-.03em', lineHeight:.92 }}>
              Fraser<span style={{ color:'var(--accent)' }}>Finds</span>
            </h1>
            <p style={{ fontFamily:'var(--serif)', fontStyle:'italic', fontSize:'clamp(18px,2.4vw,24px)', color:'var(--ink-soft)', marginTop:14 }}>
              Everything happening between the rivers — gathered up and easy to find.
            </p>
          </div>
        </div>
      </div>

      <window.SponsorStrip/>

      <div className="page-wrap" style={{ padding:'42px 28px 0' }}>
        <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:18 }}>
          <h2 style={{ fontSize:30 }}>Find your way around</h2>
          <span style={{ color:'var(--ink-faint)', fontSize:14, fontFamily:'var(--serif)', fontStyle:'italic' }}>Five places to start</span>
        </div>
        <div className="cat-grid" style={{ display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:18 }}>
          {CATS.map(c=><CatCard key={c.key} c={c} big/>)}
        </div>

        <PulpStrip/>

        <div style={{ marginTop:60 }}><EventStrip/></div>

        <div style={{ marginTop:60, borderRadius:'var(--radius-lg)', background:'var(--paper-2)', border:'1.5px solid var(--line)', padding:'38px 40px' }}>
          <div className="eyebrow">A community project for Prince George</div>
          <h2 style={{ fontSize:28, marginTop:12 }}>The goal: one place for everything happening in the city.</h2>
          <p style={{ color:'var(--ink-soft)', fontSize:16, marginTop:12, maxWidth:640, lineHeight:1.65 }}>
            Fraser Finds is a personal project — my attempt to build the most useful guide to Prince George my wife and I can.
            Every garage sale, local event, food truck, farm stand, and hidden gem in one spot.
            I'm willing to put in a fair amount of effort to make that happen, and I'm just getting started — I'm new to building websites, so bear with me while I work out the kinks.
            We recently moved to a new database and things should be significantly faster and more stable going forward.
          </p>
          <p style={{ color:'var(--ink-soft)', fontSize:16, marginTop:12, maxWidth:640, lineHeight:1.65 }}>
            I'm building community lists — great spots to eat, things to do, trails worth walking, places worth knowing about.
            If you've got a tip, a favourite local spot, or an idea for something the site should cover,
            I genuinely want to hear it.
          </p>
          <p style={{ color:'var(--ink-soft)', fontSize:15, marginTop:12, maxWidth:640, lineHeight:1.65, fontStyle:'italic' }}>
            The ads? Those are ours. My wife and I own both businesses — we thought building something useful for Prince George
            was a better way to introduce ourselves than a flyer on a telephone pole.
          </p>
          <a href="mailto:admin@fraserfinds.ca"
            style={{ display:'inline-flex', alignItems:'center', gap:8, marginTop:22, background:'var(--spruce)',
              color:'var(--paper)', fontWeight:700, fontSize:15, padding:'12px 22px', borderRadius:100,
              textDecoration:'none', letterSpacing:'.01em' }}>
            <IconMail size={17}/> Send a suggestion
          </a>
        </div>

        <div className="contour-bg" style={{ marginTop:32, borderRadius:'var(--radius-lg)', color:'var(--paper)', padding:'38px 40px',
          display:'flex', alignItems:'center', justifyContent:'space-between', gap:24, flexWrap:'wrap' }}>
          <div style={{ maxWidth:540 }}>
            <div className="eyebrow" style={{ color:'var(--accent-soft)' }}>Made by neighbours</div>
            <h2 style={{ color:'var(--paper)', fontSize:30, marginTop:12 }}>Know something we're missing?</h2>
            <p style={{ color:'rgba(248,243,225,.78)', marginTop:8, fontSize:16 }}>
              FraserFinds is built from local tips. Add a garage sale, a farm stand, a food truck, an event — anything that makes Prince George home.
            </p>
          </div>
          <button className="btn btn-primary" onClick={()=>go('submit')} style={{ fontSize:16, padding:'14px 22px' }}>
            <IconPlus size={18}/> Add a listing
          </button>
        </div>

        <div style={{ height:60 }}/>
      </div>
    </div>
  );
}

/* ============ HERO LAYOUT ============ */
function HomeHero() {
  const { go } = useFF();
  return (
    <div>
      <div style={{ position:'relative', overflow:'hidden', borderBottom:'1.5px solid var(--line)' }}>
        <div style={{ position:'absolute', inset:0, background:'linear-gradient(160deg,#41431b,#2e3012 55%,#2f6f7e)' }}/>
        <div style={{ position:'absolute', inset:0, opacity:.25,
          backgroundImage:'repeating-radial-gradient(circle at 80% 120%, transparent 0 46px, rgba(248,243,225,.5) 46px 48px)' }}/>
        <div className="page-wrap" style={{ position:'relative', padding:'84px 28px 90px', textAlign:'center', color:'var(--paper)' }}>
          <div className="eyebrow" style={{ justifyContent:'center', color:'var(--accent-soft)', marginBottom:18 }}>Prince George, British Columbia</div>
          <h1 style={{ color:'var(--paper)', fontSize:'clamp(40px,7vw,82px)', letterSpacing:'-.03em', maxWidth:900, margin:'0 auto' }}>
            Your whole town, between the two rivers.
          </h1>
          <p style={{ fontFamily:'var(--serif)', fontStyle:'italic', fontSize:'clamp(18px,2.4vw,23px)', color:'rgba(248,243,225,.85)', marginTop:18, maxWidth:600, marginInline:'auto' }}>
            Events, farm stands, food trucks, and weekend garage sales — all in one neighbourly place.
          </p>
          <div style={{ display:'flex', gap:12, justifyContent:'center', marginTop:30, flexWrap:'wrap' }}>
            <button className="btn btn-primary" onClick={()=>go('calendar')} style={{ fontSize:16, padding:'14px 24px' }}><IconCalendar size={18}/> What's on this week</button>
            <a href="/garagesales.html" className="btn btn-ghost" style={{ fontSize:16, padding:'14px 24px', color:'var(--paper)', borderColor:'rgba(248,243,225,.4)', textDecoration:'none' }}><IconPin size={18}/> Garage sale map</a>
          </div>
        </div>
      </div>
      <window.SponsorStrip/>
      <div className="page-wrap" style={{ padding:'48px 28px 0' }}>
        <div className="cat-grid" style={{ display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:16 }}>
          {CATS.map(c=><CatCard key={c.key} c={c}/>)}
        </div>
        <PulpStrip/>
        <div style={{ marginTop:56 }}><EventStrip/></div>
        <div style={{ height:60 }}/>
      </div>
    </div>
  );
}

function Home() {
  const { t } = useFF();
  return t.homeLayout === 'hero' ? <HomeHero/> : <HomeAlmanac/>;
}

window.Pages = window.Pages || {};
window.Pages.Home = Home;
