/* HTD Shared UI + Navigation context (JSX) */
(function () {
  const { useContext } = React;
  const Icon = window.HTDIcon;
  const { StatusBar, AppBar } = window.HTDShell;

  const NavCtx = React.createContext({ push(){}, pop(){}, go(){}, setPhase(){}, popToRoot(){} });
  const useNav = () => useContext(NavCtx);

  // Full-screen pushed view: status bar + back header + scroll body + optional sticky footer
  function PushView({ title, right, onBack, children, footer, noPad, accent }) {
    const nav = useNav();
    const ref = React.useRef(null);
    const footRef = React.useRef(null);
    const [footH, setFootH] = React.useState(110);
    // settle: if the CSS animation clock is throttled (frozen mid-frame), force the
    // end state once the animation should have finished (same pattern as motion.jsx)
    React.useEffect(() => {
      const t = setTimeout(() => { if (ref.current) { ref.current.style.animation = 'none'; ref.current.style.transform = 'none'; } }, 320);
      return () => clearTimeout(t);
    }, []);
    // measure the real footer height so tall (multi-row) footers never occlude
    // the bottom of the scroll content
    React.useLayoutEffect(() => {
      if (footer && footRef.current) {
        const h = footRef.current.getBoundingClientRect().height;
        if (h > 0) setFootH(Math.ceil(h) + 12);
      }
    }, [footer]);
    return (
      <div ref={ref} className="pushview grid-bg" style={{ position:'absolute', inset:0, background:'var(--void)', zIndex:50, display:'flex', flexDirection:'column' }}>
        <StatusBar />
        <AppBar variant="title" title={title} left="back" right={right || []} onLeft={onBack || (() => nav.pop())} />
        <div className="screen-body screen-enter" style={{ paddingBottom: footer ? footH : 28, paddingLeft: noPad?0:16, paddingRight: noPad?0:16 }}>
          {children}
        </div>
        {footer && (
          <div ref={footRef} style={{ position:'absolute', left:0, right:0, bottom:0, padding:'14px 16px 30px',
            background:'linear-gradient(180deg, transparent, var(--void) 32%)', zIndex:10, pointerEvents:'none' }}>
            <div style={{ pointerEvents:'auto' }}>{footer}</div>
          </div>
        )}
      </div>
    );
  }

  function SectionLabel({ children, style }) {
    return <div className="label-mono" style={{ margin:'18px 2px 9px', ...style }}>{children}</div>;
  }

  function Panel({ children, glow, pad=true, style, onClick, className }) {
    return <div onClick={onClick} className={'panel'+(glow?' panel-glow':'')+(pad?' panel-pad':'')+(className?' '+className:'')} style={style}>{children}</div>;
  }

  // segmented pill tabs (ALL / FOLLOWING / ...)
  function Segmented({ items, value, onChange, style }) {
    return (
      <div className="seg" style={style}>
        {items.map(it => (
          <button key={it} className={'seg-item'+(value===it?' active':'')} onClick={()=>onChange(it)}>{it}</button>
        ))}
      </div>
    );
  }

  // underline tabs (ANALYZE / INSIGHTS / COACH)
  function UTabs({ items, value, onChange, style }) {
    return (
      <div className="utabs" style={style}>
        {items.map(it => (
          <button key={it} className={'utab'+(value===it?' active':'')} onClick={()=>onChange(it)}>{it}</button>
        ))}
      </div>
    );
  }

  function Avatar({ color, label, size=38 }) {
    return <div className="avatar" style={{ width:size, height:size, background:color, fontSize:size*0.34 }}>{label}</div>;
  }

  // 3-up metric row (feed cards, share)
  function MetricRow({ items, big }) {
    return (
      <div className="row" style={{ gap:0 }}>
        {items.map(([v,l],i)=>(
          <div key={i} style={{ flex:1, borderLeft: i? '1px solid var(--hairline)':'none', paddingLeft: i?12:0 }}>
            <div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize: big?22:18, color:'var(--bone)', lineHeight:1 }}>{v}</div>
            <div className="label-mono" style={{ marginTop:5 }}>{l}</div>
          </div>
        ))}
      </div>
    );
  }

  function ListRow({ icon, title, sub, right, onClick, danger }) {
    return (
      <button onClick={onClick} style={{ width:'100%', display:'flex', alignItems:'center', gap:13, background:'none', border:'none',
        borderBottom:'1px solid var(--hairline)', padding:'14px 2px', cursor:'pointer', textAlign:'left' }}>
        {icon && <div style={{ width:34, height:34, borderRadius:7, background:'var(--raised-2)', border:'1px solid var(--hairline-2)', display:'grid', placeItems:'center', flex:'0 0 auto' }}>
          <Icon name={icon} size={17} color={danger?'var(--danger)':'var(--bone-muted)'} /></div>}
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontFamily:'var(--ui)', fontWeight:600, fontSize:15, color: danger?'var(--danger)':'var(--bone)' }}>{title}</div>
          {sub && <div className="label-mono" style={{ marginTop:2 }}>{sub}</div>}
        </div>
        {right!==undefined ? right : <Icon name="chevronRight" size={18} color="var(--steel)" />}
      </button>
    );
  }

  // GPS route placeholder (matches mock map preview)
  function GPSMap({ height=120 }) {
    return (
      <div style={{ position:'relative', height, borderRadius:6, overflow:'hidden',
        background:'repeating-linear-gradient(135deg, #0c0f0b 0 8px, #0a0d0a 8px 16px)' }}>
        <svg width="100%" height="100%" viewBox="0 0 300 120" preserveAspectRatio="none" style={{ position:'absolute', inset:0 }}>
          <g stroke="rgba(120,140,90,0.18)" strokeWidth="1" fill="none">
            <path d="M0 30 H300 M0 60 H300 M0 90 H300 M60 0 V120 M120 0 V120 M180 0 V120 M240 0 V120" />
          </g>
          <path d="M40 96 C70 92 78 60 110 58 C150 56 150 28 200 30 C250 32 250 46 282 22"
            fill="none" stroke="var(--acid)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
          <circle cx="40" cy="96" r="3.5" fill="var(--acid)"/>
          <circle cx="282" cy="22" r="3.5" fill="var(--acid)"/>
        </svg>
      </div>
    );
  }

  // confidence pill
  function ConfPill({ level }) {
    const c = level==='HIGH' ? 'var(--acid)' : level==='MED' ? 'var(--amber)' : 'var(--danger)';
    return <span className="label-mono" style={{ color:c, display:'inline-flex', alignItems:'center', gap:5 }}>
      <span style={{ width:6, height:6, borderRadius:'50%', background:c, boxShadow:`0 0 6px ${c}` }}/>PROOF {level}</span>;
  }

  // tactical toast — imperative, renders inside the device screen
  function toast(msg) {
    const host = document.querySelector('.device-screen');
    if (!host) return;
    host.querySelectorAll('.htd-toast').forEach(t => t.remove());
    const el = document.createElement('div');
    el.className = 'htd-toast';
    el.textContent = msg;
    host.appendChild(el);
    setTimeout(() => el.classList.add('out'), 1700);
    setTimeout(() => el.remove(), 2100);
  }
  window.HTDToast = toast;

  window.HTDUI = { NavCtx, useNav, PushView, SectionLabel, Panel, Segmented, UTabs, Avatar, MetricRow, ListRow, GPSMap, ConfPill, toast };
})();
