// home-v6.jsx — v6 /dashboard. Warm-paper coach dashboard: team-reactive
// "My Practices" (reloads on team switch), season time chart computed from
// REAL saved practices, and an anonymous sample variant (?anon=1 or signed out).
// Replaces HomeView/TopNav in home.jsx.

const H6_BG = '#f0eee9';
const H6_INK = '#16110e';
// H6_SERIF now lives in planner-v6-tokens.jsx (loaded before this file on every
// v6 page) so /app's calendar-v6 can use it too — flag f5eda01b, 2026-07-09.
const H6_MONO = '"JetBrains Mono", ui-monospace, monospace';
const H6_SANS = '-apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif';

// v8.53 (v9 pass S1/S3): `skin` prop — default 'warm' renders EXACTLY the old warm
// serif nav (dashboard/outputs untouched); skin="tool" is the tool-world chrome for
// /rotation (CLAP block lockup + sans "Practice Planner" + same link set, active tab =
// ink underline/700). One lockup per world (V9 canvas 2a): warm keeps the serif
// lockup, tool gets the CLAP block — never both on one surface.
function V6_TopNav({ active, skin = 'warm', sub }){
  if (skin === 'tool'){
    // ≤760px (canvas 1c): lockup collapses to CLAP block + the page name, the page
    // links hide, and the primary shortens to "Planner →" — all scoped classes.
    const tlink = (href, label, on)=>(
      <a key={label} href={href} className="v6tn-page" style={{ fontSize: 12.5, fontWeight: on ? 700 : 600, textDecoration:'none',
        color: on ? '#1d1d1f' : 'rgba(0,0,0,.55)', borderBottom: on ? '2px solid #16110e' : '2px solid transparent', paddingBottom: 2 }}>{label}</a>
    );
    return (
      <div style={{ height: 52, background:'#fff', borderBottom:'.5px solid rgba(0,0,0,.08)',
        display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 24px',
        position:'sticky', top: 0, zIndex: 10, fontFamily: H6_SANS }}>
        <style>{`
          @media (max-width: 760px){
            .v6tn-page, .v6tn-name, .v6tn-dot, .v6tn-btn-full { display:none !important; }
            .v6tn-sub { color:#1d1d1f !important; font-weight:700 !important; }
          }
          @media (min-width: 761px){ .v6tn-btn-short { display:none !important; } }
        `}</style>
        <a href="index.html" style={{ textDecoration:'none', color:'inherit', display:'flex', alignItems:'center', gap: 10 }}>
          <span style={{ width: 26, height: 26, borderRadius: 7, background:'#16110e', color:'#fff', display:'inline-flex',
            alignItems:'center', justifyContent:'center', fontSize: 8.5, fontWeight: 800, letterSpacing:'.02em', flexShrink: 0 }}>CLAP</span>
          <span className="v6tn-name" style={{ fontSize: 13.5, fontWeight: 700, color:'#1d1d1f', whiteSpace:'nowrap' }}>Practice Planner</span>
          {sub && <span style={{ fontSize: 13.5, color:'rgba(0,0,0,.35)', whiteSpace:'nowrap' }}><span className="v6tn-dot">· </span><span className="v6tn-sub" style={{ fontSize: 13.5 }}>{sub}</span></span>}
        </a>
        <div style={{ display:'flex', alignItems:'center', gap: 22 }}>
          {tlink('dashboard.html', 'Home', active==='home')}
          {tlink('outputs.html', 'Outputs', active==='outputs')}
          {tlink('rotation.html', 'Rotations', active==='rotations')}
          <a href="app.html" style={{ display:'inline-flex', alignItems:'center', height: 32, padding:'0 14px', borderRadius: 9,
            background:'#16110e', color:'#fff', fontSize: 12.5, fontWeight: 700, textDecoration:'none', whiteSpace:'nowrap' }}>
            <span className="v6tn-btn-full">Open planner →</span><span className="v6tn-btn-short">Planner →</span>
          </a>
        </div>
      </div>
    );
  }
  const link = (href, label, on)=>(
    <a key={label} href={href} style={{ fontSize: 13, fontWeight: on ? 700 : 500, textDecoration:'none',
      color: on ? H6_INK : 'rgba(22,17,14,.6)', borderBottom: on ? `2px solid ${H6_INK}` : '2px solid transparent', paddingBottom: 3 }}>{label}</a>
  );
  return (
    <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between',
      padding:'16px clamp(20px, 4vw, 44px)', borderBottom:'.5px solid rgba(22,17,14,.1)',
      position:'sticky', top: 0, background:'rgba(240,238,233,.9)', backdropFilter:'blur(10px)', zIndex: 10 }}>
      <a href="index.html" style={{ textDecoration:'none', display:'flex', alignItems:'baseline', gap: 9 }}>
        <span style={{ fontFamily: H6_SERIF, fontSize: 19, fontStyle:'italic', color: H6_INK }}>The Practice <b style={{ fontStyle:'normal' }}>Planner</b></span>
        <span style={{ fontSize: 9.5, letterSpacing:'.16em', textTransform:'uppercase', color:'rgba(22,17,14,.45)', fontFamily: H6_MONO }}>by CLAP</span>
      </a>
      <div style={{ display:'flex', alignItems:'center', gap: 22 }}>
        {link('dashboard.html', 'Home', active==='home')}
        {link('outputs.html', 'Outputs', active==='outputs')}
        {link('rotation.html', 'Rotations', active==='rotations')}
        <a href="app.html" style={{ background: H6_INK, color:'#f4ede2', borderRadius: 9, padding:'8px 15px',
          fontFamily: H6_SANS, fontSize: 12.5, fontWeight: 600, textDecoration:'none' }}>Open planner →</a>
      </div>
    </div>
  );
}

// per-practice category minutes (concurrency-aware via shared totals)
function v6PracticeCatMinutes(data){
  try { return totals({ start: data.start || 0, blocks: (data.blocks||[]), targetDur: data.targetDur }); }
  catch(_){ return null; }
}

function V6_HomeView(){
  const anon = (()=>{ try { return new URLSearchParams(window.location.search||'').get('anon')==='1'; } catch(_){ return false; } })();
  // Rules of Hooks: call the session/teams hooks UNCONDITIONALLY on every render.
  // The old gates — session on `!anon`, teams on `user` — made `useClaTeams()` run
  // only after auth resolved (`user` flips null→object), so the hook COUNT changed
  // between renders → React #311 "Rendered more hooks than during the previous
  // render" on /dashboard (Tim self-audit flag 50273c8a, 2026-07-12). The `typeof`
  // guard is stable per page (auth.jsx is always loaded here), matching the standard
  // call pattern in analytics.jsx / planner-v6-core.jsx. The anonymous sample variant
  // is preserved by zeroing `user` below, NOT by skipping hooks; useClaTeams is safe
  // signed-out (listTeams returns []).
  const auth = (typeof useClaSession !== 'undefined') ? useClaSession() : { user: null };
  const teamsApi = (typeof useClaTeams !== 'undefined') ? useClaTeams() : null;
  const user = anon ? null : auth.user;
  const currentTeam = (user && teamsApi) ? teamsApi.currentTeam : null;
  const [rows, setRows] = React.useState(null);
  const load = React.useCallback(async ()=>{
    if (!user || !window.listUserPractices){ setRows(null); return; }
    setRows(await window.listUserPractices());
  }, [user]);
  React.useEffect(()=>{ load(); }, [load, currentTeam && currentTeam.id]);
  React.useEffect(()=>{
    const on = ()=>load();
    window.addEventListener('cla:team-changed', on);
    return ()=>window.removeEventListener('cla:team-changed', on);
  }, [load]);

  // sample data for the anonymous variant
  const sample = React.useMemo(()=>{
    if (rows) return null;
    // D5 (v6.1): one sample story everywhere — these rows mirror the app demo's
    // tab strip (PRACTICE_HISTORY: practices #5..#2, same dates), so a prospect
    // cross-checking dashboard against the demo app sees the SAME season.
    return [1,2,3,4].map((i)=>({ id:'s'+i, name:'Practice '+(6-i), data:{ ...JSON.parse(JSON.stringify(DEFAULT_PRACTICE)),
      date: ['Thu, Mar 14','Wed, Mar 13','Tue, Mar 12','Mon, Mar 11'][i-1], num: 6-i } }));
  }, [rows]);
  const list = rows || sample || [];

  // month buckets for the season chart
  const monthAgg = React.useMemo(()=>{
    const m = new Map(); // 'YYYY-MM' -> {label, byCat}
    list.forEach((r)=>{
      const iso = v6DisplayToISO((r.data && r.data.date) || '');
      const key = iso ? iso.slice(0,7) : 'other';
      const label = iso ? new Date(key+'-02T12:00:00').toLocaleDateString('en-US',{ month:'short' }) : '—';
      const t = v6PracticeCatMinutes(r.data || {});
      if (!t) return;
      const e = m.get(key) || { label, byCat: {}, total: 0 };
      CAT_ORDER.forEach((k)=>{ e.byCat[k] = (e.byCat[k]||0) + (t.byCat[k]||0); e.total += (t.byCat[k]||0); });
      m.set(key, e);
    });
    return Array.from(m.entries()).sort((a,b)=> a[0] < b[0] ? -1 : 1).map(([,v])=>v);
  }, [list]);
  const maxMonth = Math.max(1, ...monthAgg.map((m)=>m.total));
  const seasonMin = monthAgg.reduce((s,m)=>s+m.total, 0);

  return (
    <div style={{ minHeight:'100vh', background: H6_BG, color: H6_INK, fontFamily: H6_SANS }} data-screen-label="Dashboard">
      <V6_TopNav active="home" />
      {!user && (
        <div style={{ padding:'11px clamp(20px, 4vw, 44px)', background:'#16110e', color:'#f4ede2', fontSize: 12.5, display:'flex', gap: 12, alignItems:'center' }}>
          <span style={{ fontFamily: H6_MONO, fontSize: 10, letterSpacing:'.12em' }}>SAMPLE DATA</span>
          You're looking at an example dashboard. <a href="app.html" style={{ color:'#f4ede2', fontWeight: 700 }}>Sign in</a> to see your team.
        </div>
      )}
      <div style={{ maxWidth: 1080, margin:'0 auto', padding:'40px clamp(20px, 4vw, 44px) 64px' }}>
        {/* header row */}
        <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap: 16, flexWrap:'wrap' }}>
          <div>
            <div style={{ fontSize: 11, letterSpacing:'.16em', textTransform:'uppercase', color:'rgba(22,17,14,.5)', fontFamily: H6_MONO, marginBottom: 10 }}>
              {currentTeam ? currentTeam.name : 'CLAP · sample team'} · {new Date().toLocaleDateString('en-US',{ month:'long', year:'numeric' })}
            </div>
            <h1 style={{ fontFamily: H6_SERIF, fontSize:'clamp(28px, 3.6vw, 38px)', margin: 0, letterSpacing:'-.01em' }}>
              Where is our time going?
            </h1>
          </div>
          {teamsApi && teamsApi.teams.length > 1 && (
            <select value={currentTeam ? currentTeam.id : ''} onChange={(e)=>teamsApi.setCurrent(e.target.value)}
              style={{ height: 36, padding:'0 12px', borderRadius: 9, border:'.5px solid rgba(22,17,14,.25)', background:'#fffdf6',
                fontFamily: H6_SANS, fontSize: 13, fontWeight: 600, color: H6_INK, cursor:'pointer', outline:'none' }}>
              {teamsApi.teams.map((tm)=>(<option key={tm.id} value={tm.id}>{tm.name}</option>))}
            </select>
          )}
        </div>

        {/* stat strip */}
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(150px, 1fr))', gap: 12, marginTop: 26 }}>
          {[['Practices', list.length], ['Season minutes', seasonMin >= 120 ? (seasonMin/60).toFixed(1) + ' h' : seasonMin + ' min'],
            ['Avg / practice', list.length ? Math.round(seasonMin / list.length) + ' min' : '—'],
            ['Drills in bank', currentTeam && Array.isArray(currentTeam.drill_bank) ? currentTeam.drill_bank.length : 24]].map(([k,v])=>(
            <div key={k} style={{ background:'#fffdf6', borderRadius: 14, padding:'14px 16px', boxShadow:'0 0 0 .5px rgba(22,17,14,.1)' }}>
              <div style={{ fontSize: 9.5, fontWeight: 800, letterSpacing:'.1em', textTransform:'uppercase', color:'rgba(22,17,14,.45)' }}>{k}</div>
              <div style={{ fontFamily: H6_MONO, fontSize: 24, fontWeight: 700, marginTop: 5 }}>{v}</div>
            </div>
          ))}
          <a href="rotation.html" style={{ background:'#fffdf6', borderRadius: 14, padding:'14px 16px', boxShadow:'0 0 0 .5px rgba(22,17,14,.1)',
            textDecoration:'none', color:'inherit', display:'block' }}>
            <div style={{ fontSize: 9.5, fontWeight: 800, letterSpacing:'.1em', textTransform:'uppercase', color:'rgba(22,17,14,.45)' }}>Rotation maker</div>
            <div style={{ fontFamily: H6_MONO, fontSize: 24, fontWeight: 700, marginTop: 5 }}>Open →</div>
          </a>
        </div>

        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(320px, 1fr))', gap: 18, marginTop: 18, alignItems:'start' }}>
          {/* season chart */}
          <div style={{ background:'#fffdf6', borderRadius: 16, padding: 20, boxShadow:'0 0 0 .5px rgba(22,17,14,.1)' }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, marginBottom: 4 }}>Practice time by month</div>
            <div style={{ fontSize: 11, color:'rgba(22,17,14,.5)', marginBottom: 16 }}>Minutes per category, from your saved practices.</div>
            {monthAgg.length === 0 ? (
              <div style={{ padding:'40px 0', textAlign:'center', color:'rgba(22,17,14,.45)', fontSize: 13 }}>No practices yet — plan one and it shows up here.</div>
            ) : (
              <React.Fragment>
                {/* D7 (v6.1): horizontal labeled bars — every month shows its minutes */}
                <div style={{ display:'flex', flexDirection:'column', gap: 10, padding:'4px 0 2px' }}>
                  {monthAgg.map((m, i)=>(
                    <div key={i} style={{ display:'flex', alignItems:'center', gap: 10 }}>
                      <div style={{ width: 36, flexShrink: 0, fontFamily: H6_MONO, fontSize: 10.5, color:'rgba(22,17,14,.55)' }}>{m.label}</div>
                      <div style={{ flex: 1, height: 18, borderRadius: 5, overflow:'hidden', background:'rgba(22,17,14,.05)' }}>
                        <div style={{ display:'flex', height:'100%', width: `${Math.max((m.total/maxMonth)*100, 2)}%` }}>
                          {CAT_ORDER.filter((k)=>m.byCat[k]>0).map((k)=>(
                            <div key={k} title={`${CATEGORIES[k].label} · ${m.byCat[k]} min`}
                              style={{ flex: m.byCat[k], background: CATEGORIES[k].ink }} />
                          ))}
                        </div>
                      </div>
                      <div style={{ width: 54, flexShrink: 0, textAlign:'right', fontFamily: H6_MONO, fontSize: 10.5, color:'rgba(22,17,14,.65)' }}>
                        {m.total >= 120 ? (m.total/60).toFixed(1) + ' h' : m.total + ' min'}</div>
                    </div>
                  ))}
                </div>
                <div style={{ display:'flex', gap: 12, marginTop: 14, flexWrap:'wrap' }}>
                  {CAT_ORDER.filter((k)=> monthAgg.some((m)=>m.byCat[k]>0)).map((k)=>(
                    <span key={k} style={{ display:'inline-flex', alignItems:'center', gap: 5, fontSize: 10.5, color:'rgba(22,17,14,.6)' }}>
                      <span style={{ width: 7, height: 7, borderRadius: 2, background: CATEGORIES[k].ink }} />{CATEGORIES[k].label}
                    </span>
                  ))}
                </div>
              </React.Fragment>
            )}
          </div>

          {/* my practices */}
          <div style={{ background:'#fffdf6', borderRadius: 16, padding: 20, boxShadow:'0 0 0 .5px rgba(22,17,14,.1)' }}>
            <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom: 12 }}>
              <div style={{ fontSize: 12.5, fontWeight: 700 }}>My practices</div>
              <a href="app.html" style={{ fontSize: 11.5, fontWeight: 700, color:'#c0492c', textDecoration:'none' }}>Open planner →</a>
            </div>
            {list.length === 0 ? (
              <div style={{ padding:'34px 8px', textAlign:'center', color:'rgba(22,17,14,.45)', fontSize: 13, lineHeight: 1.5 }}>
                No practices for this team yet.<br />
                <a href="app.html" style={{ color:'#c0492c', fontWeight: 700 }}>Plan your first practice →</a>
              </div>
            ) : list.slice(0, 6).map((r)=>{
              const d = r.data || {};
              const t = v6PracticeCatMinutes(d);
              return (
                <a key={r.id} href={user ? `app.html?practice=${r.id}` : 'app.html'}
                  style={{ display:'flex', alignItems:'center', gap: 12, padding:'11px 10px', margin:'0 -10px', borderRadius: 10,
                    textDecoration:'none', color:'inherit' }}
                  onMouseEnter={(e)=>e.currentTarget.style.background='rgba(22,17,14,.04)'}
                  onMouseLeave={(e)=>e.currentTarget.style.background='transparent'}>
                  <div style={{ width: 74, flexShrink: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 700 }}>{String(d.date||'').replace(/^\w+,\s*/,'')}</div>
                    <div style={{ fontFamily: H6_MONO, fontSize: 9.5, color:'rgba(22,17,14,.45)' }}>№ {d.num != null ? d.num : '—'}</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{d.emphasis || r.name}</div>
                    {t && (
                      <div style={{ display:'flex', height: 5, borderRadius: 3, overflow:'hidden', marginTop: 6, background:'rgba(22,17,14,.05)', maxWidth: 260 }}>
                        {CAT_ORDER.filter((k)=>t.byCat[k]>0).map((k)=>(
                          <div key={k} style={{ flex: t.byCat[k], background: CATEGORIES[k].ink }} />
                        ))}
                      </div>
                    )}
                  </div>
                  <div style={{ fontFamily: H6_MONO, fontSize: 11, color:'rgba(22,17,14,.55)', flexShrink: 0, minWidth: 52, textAlign:'right', marginLeft: 8 }}>{t ? t.totalMin + ' min' : ''}</div>
                </a>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { V6_HomeView, V6_TopNav });
