// Theme-aware shared components for the overhaul. Written against the CSS vars
// in theme.jsx so they flip light/dark and retint with the accent automatically.

(function () {
const { useState, useEffect, useRef } = React;
const { cx, wash } = LMTXUtil;
const I = window.LMTIcons;

// ── Avatar (initials) ──────────────────────────────────────────────────────
function Avatar({ name, color = '#15803d', size = 32, ring = false, glow = false, here = false }) {
  const initials = name.split(/[\s.]+/).filter(Boolean).slice(0,2).map(w => w[0]).join('').toUpperCase();
  return (
    <span style={{ position:'relative', flex:'0 0 auto', width:size, height:size }}>
      <span style={{
        width:size, height:size, borderRadius:'50%', display:'grid', placeItems:'center',
        background:`linear-gradient(140deg, ${color}, ${wash(color,0.62)})`, color:'#fff',
        fontSize:size*0.38, fontWeight:700, letterSpacing:'-0.02em',
        boxShadow: glow ? `0 0 0 1px ${wash(color,0.4)}, 0 4px 14px -4px ${color}` : 'inset 0 0 0 1px rgba(255,255,255,.18)',
        border: ring ? '2px solid var(--raised)' : 'none', fontFamily:'Geist, sans-serif',
      }}>{initials}</span>
      {here && <span className="live" style={{ position:'absolute', right:-1, bottom:-1, width:size*0.3, height:size*0.3, minWidth:9, minHeight:9, borderRadius:'50%', background:'#22c55e', border:'2px solid var(--raised)' }}/>}
    </span>
  );
}

// ── Page header ─────────────────────────────────────────────────────────────
function PageHead({ kicker, title, sub, right, icon }) {
  return (
    <div style={{ display:'flex', alignItems:'flex-end', gap:16, flexWrap:'wrap' }}>
      <div style={{ flex:1, minWidth:0 }}>
        {kicker && <div className="mono" style={{ fontSize:11, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--faint)', marginBottom:7, display:'flex', alignItems:'center', gap:7 }}>{icon && <span style={{ fontSize:13, color:'var(--accent)' }}>{icon}</span>}{kicker}</div>}
        <h1 className="disp" style={{ fontSize:'clamp(24px, 3.4vw, 34px)', fontWeight:600, lineHeight:1.05, margin:0, letterSpacing:'-0.03em', textWrap:'balance' }}>{title}</h1>
        {sub && <p style={{ margin:'9px 0 0', color:'var(--muted)', fontSize:14.5, maxWidth:560, lineHeight:1.5, textWrap:'pretty' }}>{sub}</p>}
      </div>
      {right && <div style={{ flex:'0 0 auto', display:'flex', gap:9, alignItems:'center' }}>{right}</div>}
    </div>
  );
}

// ── Section header ──────────────────────────────────────────────────────────
function SectionHead({ title, count, right, sub }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ display:'flex', alignItems:'baseline', gap:8, flexWrap:'wrap' }}>
          <h2 className="disp" style={{ fontSize:16.5, fontWeight:600, margin:0, letterSpacing:'-0.02em', whiteSpace:'nowrap', flexShrink:0 }}>{title}</h2>
          {count != null && <span className="mono tnum" style={{ fontSize:12, color:'var(--faint)' }}>{count}</span>}
        </div>
        {sub && <div style={{ fontSize:12.5, color:'var(--faint)', marginTop:3 }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

// ── Theme-aware event card (leaf metaphor preserved) ────────────────────────
function LeafCard({ event, dense = false, onClick, i = 0, surface = 'card' }) {
  const c = LMT.leafFor(event.daysSince);
  const m = LMT.mood[event.mood] || LMT.mood[3];
  return (
    <div className={cx('lift press', surface === 'card' && 'card')} onClick={onClick} style={{
      display:'flex', alignItems:'flex-start', gap:12, padding: dense ? '11px 13px' : '14px 15px',
      cursor:'pointer', '--i':i, borderRadius:'var(--radius)',
      background: surface === 'sunk' ? 'var(--sunken)' : undefined,
      border: surface === 'sunk' ? '1px solid var(--hair)' : undefined,
    }}>
      <div style={{ position:'relative', flex:'0 0 auto', paddingTop:2 }}>
        <LeafShape color={c} size={dense ? 24 : 30} rotate={-22 + (event.id.charCodeAt(2) % 30)} />
        {event.fragile && <span title="Fragile memory" style={{ position:'absolute', top:-1, right:-3, width:8, height:8, borderRadius:'50%', background:'#dc2626', border:'1.5px solid var(--raised)' }}/>}
      </div>
      <div style={{ flex:1, minWidth:0 }}>
        <div className="disp" style={{ fontSize: dense ? 14 : 15.5, lineHeight:1.3, fontWeight:550, color:'var(--ink)', textWrap:'pretty' }}>{event.title}</div>
        <div style={{ display:'flex', alignItems:'center', gap:7, marginTop:5, color:'var(--faint)', fontSize:11.5, flexWrap:'wrap' }}>
          <span className="mono tnum">{event.t}</span>
          <Dot/><span style={{ color:'var(--muted)' }}>{event.scene}</span>
          {event.place && <><Dot/><span>{event.place.split(' · ')[0]}</span></>}
        </div>
        {!dense && event.tags?.length > 0 && (
          <div style={{ display:'flex', flexWrap:'wrap', gap:5, marginTop:8 }}>
            {event.tags.slice(0,3).map(t => <span key={t} className="mono" style={{ fontSize:10.5, color:'var(--muted)', background:'var(--sunken)', padding:'2px 7px', borderRadius:6, border:'1px solid var(--hair)' }}>#{t}</span>)}
          </div>
        )}
      </div>
      <div style={{ flex:'0 0 auto', display:'flex', flexDirection:'column', alignItems:'flex-end', gap:7, paddingTop:2 }}>
        <span style={{ width:10, height:10, borderRadius:'50%', background:m.color, boxShadow:'inset 0 0 0 1px rgba(0,0,0,.12)' }} title={`mood · ${m.label}`}/>
        {event.links > 0 && <span className="mono tnum" style={{ fontSize:11, color:'var(--faint)', display:'inline-flex', alignItems:'center', gap:3 }}><I.Link style={{ fontSize:11 }}/>{event.links}</span>}
      </div>
    </div>
  );
}
function Dot() { return <span style={{ color:'var(--ghost)' }}>·</span>; }

// ── Stat tile ───────────────────────────────────────────────────────────────
function StatTile({ label, value, unit, trend, accent, icon, i = 0 }) {
  return (
    <div className="card-r lift" style={{ padding:16, '--i':i, position:'relative', overflow:'hidden' }}>
      {accent && <div style={{ position:'absolute', top:0, left:0, right:0, height:3, background:accent }}/>}
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10 }}>
        <span className="mono" style={{ fontSize:10.5, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--faint)' }}>{label}</span>
        {icon && <span style={{ fontSize:15, color: accent || 'var(--accent)' }}>{icon}</span>}
      </div>
      <div style={{ display:'flex', alignItems:'baseline', gap:5 }}>
        <span className="disp tnum" style={{ fontSize:28, fontWeight:600, letterSpacing:'-0.03em' }}>{value}</span>
        {unit && <span style={{ fontSize:13, color:'var(--faint)' }}>{unit}</span>}
      </div>
      {trend && <div style={{ fontSize:11.5, color: trend.up ? '#16a34a' : 'var(--muted)', marginTop:5, display:'flex', alignItems:'center', gap:4 }}>{trend.up ? '↑' : '↓'} {trend.text}</div>}
    </div>
  );
}

// ── Segmented tabs ──────────────────────────────────────────────────────────
function SegTabs({ tabs, value, onChange, size = 'md' }) {
  const pad = size === 'sm' ? '5px 11px' : '7px 14px';
  const fs = size === 'sm' ? 12 : 13;
  return (
    <div style={{ display:'inline-flex', padding:3, gap:2, background:'var(--sunken)', borderRadius:11, border:'1px solid var(--hair)' }}>
      {tabs.map(t => {
        const active = (t.id ?? t) === value;
        return (
          <button key={t.id ?? t} onClick={() => onChange(t.id ?? t)} className="press" style={{
            display:'inline-flex', alignItems:'center', gap:6, padding:pad, borderRadius:8, border:'none', cursor:'pointer',
            fontFamily:'inherit', fontSize:fs, fontWeight:600, whiteSpace:'nowrap',
            background: active ? 'var(--raised)' : 'transparent', color: active ? 'var(--ink)' : 'var(--muted)',
            boxShadow: active ? 'var(--shadow-pop)' : 'none', transition:'all .18s cubic-bezier(.2,.7,.2,1)',
          }}>{t.icon}{t.label ?? t}</button>
        );
      })}
    </div>
  );
}

// ── Toggle ──────────────────────────────────────────────────────────────────
function Toggle({ on, onChange, size = 22 }) {
  return (
    <button onClick={() => onChange(!on)} className="press" style={{
      width:size*1.85, height:size, borderRadius:999, border:'none', cursor:'pointer', padding:2,
      background: on ? 'var(--accent)' : 'var(--edge-strong)', transition:'background .22s ease', position:'relative',
    }}>
      <span style={{ display:'block', width:size-4, height:size-4, borderRadius:'50%', background:'#fff',
        transform: on ? `translateX(${size*0.85}px)` : 'translateX(0)', transition:'transform .24s cubic-bezier(.2,.8,.2,1)', boxShadow:'0 1px 3px rgba(0,0,0,.3)' }}/>
    </button>
  );
}

// ── Mini bar chart ──────────────────────────────────────────────────────────
function Bars({ data, color, height = 56, labels, max }) {
  const mx = max || Math.max(...data);
  return (
    <div style={{ display:'flex', alignItems:'flex-end', gap:'4%', height, width:'100%' }}>
      {data.map((v, i) => (
        <div key={i} style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:5, height:'100%', justifyContent:'flex-end' }}>
          <div className="lx-grow" style={{ width:'100%', height:`${(v/mx)*100}%`, minHeight:3, borderRadius:'4px 4px 2px 2px',
            background: color || 'var(--accent)', opacity:0.35 + 0.65*(v/mx),
            animation:`lmtx-grow calc(.8s*var(--mo)) cubic-bezier(.2,.8,.2,1) both`, animationDelay:`calc(${i}*.04s*var(--mo))` }}/>
          {labels && <span className="mono" style={{ fontSize:9, color:'var(--faint)' }}>{labels[i]}</span>}
        </div>
      ))}
    </div>
  );
}

// ── Visibility lozenge (theme-aware) ────────────────────────────────────────
function Vis({ v = 'private', size = 'sm' }) {
  const map = { private:{I:I.Lock,l:'Private',c:'var(--muted)'}, scene:{I:I.Eye,l:'Scene',c:'#d97706'}, public:{I:I.Globe,l:'Public',c:'#16a34a'} };
  const m = map[v];
  const fs = size === 'xs' ? 9.5 : 11;
  return <span className="pill" style={{ color:m.c, fontSize:fs, padding: size==='xs'?'2px 7px':'4px 9px' }}><m.I style={{ fontSize:fs+1 }}/>{m.l}</span>;
}

// ── Empty/coachmark hint ────────────────────────────────────────────────────
function Hint({ icon, children }) {
  return (
    <div style={{ display:'flex', gap:10, alignItems:'flex-start', padding:'12px 14px', background:'var(--accent-wash)', border:'1px solid var(--accent-line)', borderRadius:12, color:'var(--ink)', fontSize:13, lineHeight:1.5 }}>
      <span style={{ color:'var(--accent)', fontSize:16, flex:'0 0 auto', marginTop:1 }}>{icon || <I.Sparkles/>}</span>
      <span style={{ color:'var(--muted)' }}>{children}</span>
    </div>
  );
}

Object.assign(window, { Avatar, PageHead, SectionHead, LeafCard, StatTile, SegTabs, Toggle, Bars, Vis, Hint });
})();
