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

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

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 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) : 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>
  );
}

function SponsorStrip() {
  const [sponsors, setSponsors] = React.useState([]);
  const [idx, setIdx] = React.useState(0);

  React.useEffect(() => {
    fetch('/sponsors/sponsors.txt')
      .then(r => r.text())
      .then(txt => {
        const list = txt.split('\n')
          .map(l => l.trim())
          .filter(l => l && !l.startsWith('#'))
          .map(l => {
            const [logo, banner, name, url] = l.split('|').map(s => s.trim());
            return { logo: `/sponsors/${logo}`, banner: `/sponsors/${banner}`, name, url };
          })
          .filter(s => s.name && s.url);
        setSponsors(list);
      })
      .catch(() => {});
  }, []);

  React.useEffect(() => {
    if (sponsors.length < 2) return;
    const t = setInterval(() => setIdx(i => (i + 1) % sponsors.length), 30000);
    return () => clearInterval(t);
  }, [sponsors.length]);

  if (sponsors.length === 0) return null;
  const s = sponsors[idx];

  return (
    <div style={{ marginTop:40, borderTop:'1.5px solid var(--line)', borderBottom:'1.5px solid var(--line)' }}>
      <div style={{ fontSize:11, fontWeight:700, letterSpacing:'.14em', textTransform:'uppercase', color:'var(--ink-faint)', textAlign:'center', padding:'18px 0 14px' }}>Brought to you by</div>
      <a href={s.url} target="_blank" rel="noopener" title={s.name} style={{ display:'block' }}>
        <img src={s.banner} alt={s.name} style={{ display:'block', width:'100%', maxHeight:160, objectFit:'contain', opacity:.95 }}/>
      </a>
    </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>

      <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' }}>Four 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>

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

        <div className="contour-bg" style={{ marginTop:60, 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>

        <SponsorStrip/>
        <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>
      <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>
        <div style={{ marginTop:56 }}><EventStrip/></div>
        <SponsorStrip/>
        <div style={{ height:60 }}/>
      </div>
    </div>
  );
}

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

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