const { Button, Card } = window.FamilyFitDesignSystem_42efdd;

const FAMILY = [
  {name:'Papai', seed:0, weekPts:1420, monthPts:5320, allPts:42800, streak:6, team:'D3'},
  {name:'Ayam', seed:2, weekPts:1340, monthPts:5760, allPts:36100, streak:9, team:'D3'},
  {name:'Ti Tio', seed:1, weekPts:1180, monthPts:4900, allPts:38500, streak:4, team:'D2'},
  {name:'Sab', seed:3, weekPts:860, monthPts:3400, allPts:24700, streak:3, team:'D3'},
  {name:'Mayday', seed:4, weekPts:640, monthPts:2500, allPts:18300, streak:2, team:'D2'},
];

const ACTIVITIES = [
  {name:'Walking', tone:'stretch', icon:'ph-person-simple-walk', category:'Outdoor', desc:'The easiest way to start. Every step counts toward the family total.', stat:'Most logged activity'},
  {name:'Running', tone:'run', icon:'ph-person-simple-run', category:'Cardio', desc:'From a quick jog round the block to a proper 10k.', stat:'Fastest way to build a streak'},
  {name:'Cycling', tone:'cycle', icon:'ph-bicycle', category:'Outdoor', desc:'On the road, on the trail, or on a stationary bike.', stat:'Best for longer distances'},
  {name:'Swimming', tone:'swim', icon:'ph-waves', category:'Cardio', desc:'Lengths at the local pool, or open water when the weather allows.', stat:'Low impact, high reward'},
  {name:'Football', tone:'strength', icon:'ph-soccer-ball', category:'Team', desc:'Five-a-side, a kickabout in the park, or a proper match.', stat:'Best logged as a team'},
  {name:'Cricket', tone:'strength', icon:'ph-cricket', category:'Team', desc:'A back-garden game or a proper match on the green.', stat:'Great for a full afternoon out'},
  {name:'Rounders', tone:'stretch', icon:'ph-baseball', category:'Team', desc:'Easy to pick up and brilliant for mixed ages.', stat:'A family favourite at the park'},
  {name:'Tennis', tone:'run', icon:'custom:tennis', category:'Cardio', desc:'A quick knock-about or a proper set.', stat:'Best with a partner'},
  {name:'Gym', tone:'strength', icon:'ph-barbell', category:'Cardio', desc:'Weights, machines, or a class — whatever suits.', stat:'Structured strength, your way'},
  {name:'Netball', tone:'cycle', icon:'custom:netball', category:'Team', desc:'Fast-paced and easy to organise with a few people.', stat:'Great for building teamwork'},
  {name:'Rowing', tone:'swim', icon:'img:rowing-icon.png', category:'Outdoor', desc:'On the water or on a machine at the gym.', stat:'A full-body session'},
  {name:'Others', tone:'run', icon:'ph-fill ph-dots-three-outline', category:'Other', desc:'Anything else that gets you moving.', stat:'Every bit of activity counts'},
];

const CustomSportIcons = {
  tennis: (p)=>{
    const diag = [];
    for(let i=-100;i<=220;i+=20){
      diag.push(<line key={'a'+i} x1={i} y1={-30} x2={i+140} y2={170} strokeWidth="5"/>);
      diag.push(<line key={'b'+i} x1={i} y1={170} x2={i+140} y2={-30} strokeWidth="5"/>);
    }
    return (
      <svg viewBox="0 0 256 256" fill="none" stroke="currentColor" strokeWidth="14" strokeLinecap="round" strokeLinejoin="round" {...p}>
        <g transform="rotate(38 128 128)">
          <defs><clipPath id="tnsClip"><ellipse cx="128" cy="70" rx="50" ry="64"/></clipPath></defs>
          <g clipPath="url(#tnsClip)">{diag}</g>
          <ellipse cx="128" cy="70" rx="50" ry="64"/>
          <path d="M106 126 Q120 148 128 162"/>
          <path d="M150 126 Q136 148 128 162"/>
          <line x1="128" y1="160" x2="128" y2="248"/>
          <line x1="115" y1="212" x2="141" y2="212" strokeWidth="8"/>
          <line x1="115" y1="230" x2="141" y2="230" strokeWidth="8"/>
        </g>
      </svg>
    );
  },
  rowing: (p)=>(
    <svg viewBox="0 0 256 256" fill="none" stroke="currentColor" strokeWidth="14" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M30 168 Q128 148 226 168 Q194 198 128 198 Q62 198 30 168 Z"/>
      <circle cx="122" cy="104" r="16"/>
      <line x1="122" y1="122" x2="122" y2="160"/>
      <line x1="122" y1="136" x2="196" y2="112"/>
      <line x1="182" y1="100" x2="210" y2="122" strokeWidth="10"/>
      <path d="M18 220 Q40 208 62 220 T106 220 T150 220 T194 220 T238 220" strokeWidth="8"/>
    </svg>
  ),
  netball: (p)=>(
    <svg viewBox="0 0 256 256" fill="none" stroke="currentColor" strokeWidth="14" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <line x1="128" y1="234" x2="128" y2="118"/>
      <ellipse cx="128" cy="86" rx="48" ry="16"/>
      <g strokeWidth="7">
        <line x1="92" y1="92" x2="100" y2="150"/><line x1="112" y1="90" x2="118" y2="156"/><line x1="128" y1="90" x2="128" y2="160"/><line x1="144" y1="90" x2="138" y2="156"/><line x1="164" y1="92" x2="156" y2="150"/>
      </g>
    </svg>
  ),
  hockey: (p)=>(
    <svg viewBox="0 0 256 256" fill="none" stroke="currentColor" strokeWidth="14" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M168 24 L112 188"/>
      <path d="M112 188 Q96 218 136 222"/>
      <circle cx="76" cy="226" r="13" fill="currentColor" stroke="none"/>
    </svg>
  ),
};

function ActivityIconBadge({a,size=40,iconSize=20}){
  const custom = a.icon.startsWith('custom:');
  const isImg = a.icon.startsWith('img:');
  const Cmp = custom ? CustomSportIcons[a.icon.slice(7)] : null;
  return (
    <span style={{width:size,height:size,borderRadius:'50%',background:`var(--color-activity-${a.tone})`,color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
      {isImg ? <img src={a.icon.slice(4)} style={{width:iconSize*1.6,height:iconSize*1.6,objectFit:'contain'}} alt="" /> : custom ? <Cmp style={{width:iconSize,height:iconSize}}/> : <i className={"ph "+a.icon} style={{fontSize:iconSize}}></i>}
    </span>
  );
}

const SUPABASE_URL = 'https://nsjtzacljajgydoqkobh.supabase.co';
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5zanR6YWNsamFqZ3lkb3Frb2JoIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODgxODM5OTMsImV4cCI6MjEwMzc1OTk5M30.M4utngW-ogQfZJeeZmB5iQvMLtZJluWBt0KXdH1QfQM';
const supabaseClient = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

async function fetchAllLogs(){
  const { data, error } = await supabaseClient.from('logs').select('*').order('logged_at', { ascending:false });
  if(error){ console.error('Failed to load logs from Supabase', error); return []; }
  return data.map(r=>({ id:r.id, activity:r.activity, person:r.person, date:r.date, duration:r.duration, format:r.format, sport:r.sport, note:r.note, loggedAt:r.logged_at, seed:r.seed }));
}

function filterActivityLogs(allLogs, activityName){
  return allLogs.filter(l=>l.activity===activityName);
}

async function addLogEntry(activityName, entry){
  const { error } = await supabaseClient.from('logs').insert({
    activity: activityName,
    person: entry.person,
    date: entry.date,
    duration: entry.duration===undefined ? null : entry.duration,
    format: entry.format===undefined ? null : entry.format,
    sport: entry.sport===undefined ? null : entry.sport,
    note: entry.note || null,
    logged_at: entry.loggedAt,
    seed: false,
  });
  if(error){ console.error('Failed to save entry to Supabase', error); throw error; }
}

async function deleteLogEntry(id){
  const { error } = await supabaseClient.from('logs').delete().eq('id', id);
  if(error){ console.error('Failed to delete entry from Supabase', error); throw error; }
}

function getTodayUTC(){
  // "Today" as UTC midnight of the viewer's local calendar date, so it lines up
  // with log dates (plain YYYY-MM-DD strings, which JS always parses as UTC midnight)
  // regardless of the viewer's timezone.
  const now = new Date();
  return new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
}

function computeFamilyPoints(allLogs){
  const today = getTodayUTC();
  const weekStart = new Date(today); weekStart.setUTCDate(today.getUTCDate()-((today.getUTCDay()+6)%7));
  const points = {};
  FAMILY.forEach(f=>{ points[f.name] = {weekPts:0,monthPts:0,allPts:0}; });
  allLogs.forEach(l=>{
    if(!points[l.person]) return;
    const d = new Date(l.date);
    if(isNaN(d)) return;
    const pts = 1;
    points[l.person].allPts += pts;
    if(d.getUTCFullYear()===today.getUTCFullYear() && d.getUTCMonth()===today.getUTCMonth()) points[l.person].monthPts += pts;
    if(d>=weekStart && d<=today) points[l.person].weekPts += pts;
  });
  return points;
}

function Reveal({children,className}){
  const ref = React.useRef(null);
  const [vis,setVis] = React.useState(false);
  React.useEffect(()=>{
    const el = ref.current;
    if(!el) return;
    const io = new IntersectionObserver(([e])=>{if(e.isIntersecting){setVis(true);io.disconnect();}},{threshold:0,rootMargin:'0px 0px 100px 0px'});
    io.observe(el);
    return ()=>io.disconnect();
  },[]);
  return <div ref={ref} className={"reveal"+(vis?" in":"")+(className?" "+className:"")}>{children}</div>;
}

function SiteHeader({active}){
  const [open,setOpen] = React.useState(false);
  const [loggedIn,setLoggedIn] = React.useState(()=>sessionStorage.getItem('ff_logged_in')==='1');
  const [confirmOpen,setConfirmOpen] = React.useState(false);
  const links = [['Home','index.html'],['About','about.html'],['Activities','activities.html'],['Leaderboard','leaderboard.html']];
  function handleCta(){
    if(loggedIn){ setConfirmOpen(true); setOpen(false); }
    else window.location.href='login.html';
  }
  function confirmLogout(){
    sessionStorage.removeItem('ff_logged_in');
    setLoggedIn(false);
    setConfirmOpen(false);
    window.location.href='index.html';
  }
  return (
    <header className="site-header">
      <div className="site-header-inner">
        <a href="index.html" className="site-logo"><img src="logo-footprints.png" alt="" className="site-logo-icon" />Family ExercisE Tournament</a>
        <nav className="site-nav-desktop">
          {links.map(([label,href])=>(
            <a key={label} href={href} className={"site-nav-link"+(active===label?" active":"")}>{label}</a>
          ))}
        </nav>
        <div className="site-header-cta"><Button variant="primary" size="sm" onClick={handleCta}>{loggedIn?'Log out':'Log in'}</Button></div>
        <button className="site-menu-btn" aria-label={open?"Close menu":"Open menu"} aria-expanded={open} onClick={()=>setOpen(!open)}>
          <i className={open?"ph ph-x":"ph ph-list"}></i>
        </button>
      </div>
      <div className={"site-nav-mobile"+(open?" open":"")}>
        <div className="site-nav-mobile-inner">
          {links.map(([label,href])=>(
            <a key={label} href={href} className={"site-nav-mobile-link"+(active===label?" active":"")} onClick={()=>setOpen(false)}>{label}</a>
          ))}
          <div style={{marginTop:8}}><Button variant="primary" onClick={handleCta}>{loggedIn?'Log out':'Log in'}</Button></div>
        </div>
      </div>
      {confirmOpen && (
        <div className="logout-scrim" onClick={()=>setConfirmOpen(false)}>
          <div className="logout-modal" onClick={e=>e.stopPropagation()}>
            <h3>Log out</h3>
            <p>Are you sure you want to log out?</p>
            <div className="logout-modal-actions">
              <Button variant="secondary" onClick={()=>setConfirmOpen(false)}>Cancel</Button>
              <Button variant="primary" onClick={confirmLogout}>Log out</Button>
            </div>
          </div>
        </div>
      )}
    </header>
  );
}

function SiteFooter(){
  return (
    <footer className="site-footer">
      <div className="site-footer-inner">
        <div>
          <div className="site-footer-logo"><img src="logo-footprints.png" alt="" className="site-footer-logo-icon" />Family Exercise Tournament</div>
          <p className="site-footer-desc">Helping families in Chester and beyond stay active together.</p>
        </div>
        <div className="site-footer-cols">
          <div>
            <div className="site-footer-heading">Explore</div>
            <a href="index.html">Home</a>
            <a href="about.html">About</a>
            <a href="activities.html">Activities</a>
            <a href="leaderboard.html">Leaderboard</a>
          </div>
          <div>
            <div className="site-footer-heading"></div>
            <a href="mailto:hello@familyfit.example"></a>
            <span className="site-footer-text"></span>
          </div>
        </div>
      </div>
      <div className="site-footer-bottom">© 2026 Family Fit. All rights reserved.</div>
    </footer>
  );
}

function computeWeeklyStats(allLogs){
  const today = getTodayUTC();
  const weekStart = new Date(today); weekStart.setUTCDate(today.getUTCDate()-((today.getUTCDay()+6)%7));
  let totalMinutes = 0, count = 0;
  const days = new Set();
  allLogs.forEach(l=>{
    const d = new Date(l.date);
    if(isNaN(d)) return;
    days.add(d.toISOString().slice(0,10));
    if(d>=weekStart && d<=today){
      count++;
      if(l.duration) totalMinutes += parseInt(l.duration)||0;
    }
  });
  let streak = 0;
  let cursor = new Date(today);
  while(days.has(cursor.toISOString().slice(0,10))){
    streak++;
    cursor.setUTCDate(cursor.getUTCDate()-1);
  }
  const h = Math.floor(totalMinutes/60), m = totalMinutes%60;
  return { activityLabel: totalMinutes>0 ? `${h}h ${m}m` : '0m', count, streak };
}

window.FamilyFitShared = { FAMILY, ACTIVITIES, Reveal, SiteHeader, SiteFooter, ActivityIconBadge, fetchAllLogs, filterActivityLogs, addLogEntry, deleteLogEntry, computeFamilyPoints, computeWeeklyStats };
