// Fill by Flow — UI primitives
// Shared components: TopBar, Waveform, FluidMeter, MicSlab, etc.

const { useState, useEffect, useRef } = React;

// ══ TOP BAR ═══════════════════════════════════════════
function TopBar({ wake, onHistory, onHome }) {
  return (
    <div style={fbfStyles.topBar}>
      <div style={fbfStyles.brand} onClick={onHome}>
        <div style={fbfStyles.bMark}>
          <div style={{...fbfStyles.bm, width:16, height:3}} />
          <div style={{...fbfStyles.bm, width:10, height:3}} />
          <div style={{...fbfStyles.bm, width:16, height:3}} />
        </div>
        <div>
          <div style={fbfStyles.bName}>
            FILL <span style={{color:'var(--accent)',fontStyle:'normal'}}>·</span> FLOW
          </div>
          <div style={fbfStyles.bSub}>Voice Fluid Engine</div>
        </div>
      </div>
      <div style={fbfStyles.topRight}>
        <div style={fbfStyles.wakePill}>
          <div style={{
            ...fbfStyles.wakeDot,
            background: wake ? 'var(--accent)' : 'var(--dim)',
            boxShadow: wake ? '0 0 6px var(--acc-glow)' : 'none'
          }} />
          <span>{wake ? "LISTENING" : "SCREEN OFF"}</span>
        </div>
        <button style={fbfStyles.histBtn} onClick={onHistory} aria-label="History">
          <div style={{height:2.5,width:18,background:'var(--mid)',borderRadius:1}} />
          <div style={{height:2.5,width:12,background:'var(--mid)',borderRadius:1,marginLeft:'auto'}} />
          <div style={{height:2.5,width:18,background:'var(--mid)',borderRadius:1}} />
        </button>
      </div>
    </div>
  );
}

// ══ WAVEFORM ══════════════════════════════════════════
function Waveform({ active }) {
  const heights = [8, 18, 32, 46, 54, 56, 54, 46, 32, 18, 8];
  const delays = [0, .07, .14, .21, .28, .35, .28, .21, .14, .07, 0];
  return (
    <div style={fbfStyles.waveform}>
      {heights.map((h, i) => (
        <div key={i} style={{
          flex:1, borderRadius:2, background:'var(--accent)',
          opacity: active ? 1 : 0.14,
          minWidth:8, height:h,
          animation: active ? `fbf-wv 1s ease-in-out ${delays[i]}s infinite` : 'none'
        }} />
      ))}
    </div>
  );
}

// ══ MIC SLAB ══════════════════════════════════════════
function MicSlab({ listening, label, onTap }) {
  return (
    <button style={{
      ...fbfStyles.micBtn,
      ...(listening ? { animation:'fbf-mpulse 1.5s ease-in-out infinite' } : {})
    }} onClick={onTap}>
      <div style={{
        position:'absolute', inset:0,
        background:'repeating-linear-gradient(-45deg, transparent 0, transparent 8px, rgba(0,0,0,0.08) 8px, rgba(0,0,0,0.08) 16px)',
        pointerEvents:'none'
      }} />
      <svg width="34" height="34" viewBox="0 0 28 28" fill="none" style={{position:'relative',zIndex:1}}>
        <rect x="10" y="2" width="8" height="15" rx="4" fill="#0A0F0A"/>
        <path d="M5 13c0 4.97 4.03 9 9 9s9-4.03 9-9" stroke="#0A0F0A" strokeWidth="2.5" strokeLinecap="round"/>
        <line x1="14" y1="22" x2="14" y2="26" stroke="#0A0F0A" strokeWidth="2.5" strokeLinecap="round"/>
        <line x1="10" y1="26" x2="18" y2="26" stroke="#0A0F0A" strokeWidth="2.5" strokeLinecap="round"/>
      </svg>
      <span style={fbfStyles.micLabel}>{label}</span>
    </button>
  );
}

// ══ FLUID METER — vertical liquid fill ═══════════════
function FluidMeter({ value, max, units, label, density = "medium", size = "large" }) {
  const pct = Math.min(100, Math.max(0, (value / max) * 100));
  const w = size === "large" ? 80 : 48;
  const h = size === "large" ? 220 : 120;

  return (
    <div style={{
      display:'flex', flexDirection:'column', alignItems:'center', gap:8,
      userSelect:'none'
    }}>
      <div style={{
        position:'relative', width: w, height: h,
        border:'2px solid var(--border-h)',
        background:'var(--panel-2)',
        overflow:'hidden'
      }}>
        {/* fill */}
        <div style={{
          position:'absolute', left:0, right:0, bottom:0,
          height: pct + '%',
          background: density === "industrial"
            ? 'var(--accent)'
            : 'linear-gradient(180deg, var(--accent) 0%, color-mix(in oklch, var(--accent), #000 25%) 100%)',
          transition: 'height 0.6s cubic-bezier(.2,.8,.2,1)',
          boxShadow: density !== "industrial" ? 'inset 0 12px 20px -8px rgba(255,255,255,0.25)' : 'none'
        }} />
        {/* meniscus curve — fluid metaphor */}
        {density !== "industrial" && pct > 2 && pct < 98 && (
          <div style={{
            position:'absolute', left:-2, right:-2,
            bottom: `calc(${pct}% - 4px)`,
            height: 8,
            background: 'radial-gradient(ellipse at 50% 0%, var(--accent) 30%, transparent 70%)',
            opacity: 0.7,
            pointerEvents:'none',
            animation: density === "heavy" ? 'fbf-slosh 3.4s ease-in-out infinite' : 'none'
          }} />
        )}
        {/* tick marks */}
        {[25, 50, 75].map((t) => (
          <div key={t} style={{
            position:'absolute', right:0, top:`${100-t}%`,
            width:8, height:1, background:'var(--border-h)'
          }} />
        ))}
        {/* pct overlay text */}
        <div style={{
          position:'absolute', top:4, left:0, right:0, textAlign:'center',
          fontFamily:"'DM Mono',monospace", fontSize:9,
          color:'var(--muted)', letterSpacing:'0.12em'
        }}>{pct.toFixed(0)}%</div>
      </div>
      {label && (
        <div style={{
          fontFamily:"'DM Mono',monospace", fontSize:9,
          color:'var(--muted)', letterSpacing:'0.16em', textTransform:'uppercase'
        }}>{label}</div>
      )}
    </div>
  );
}

// ══ SIDE RAIL — dashed accent bar ═════════════════════
function SideRail() {
  return (
    <div style={{
      position:'absolute', left:0, top:'8%', bottom:'8%', width:4,
      background:'repeating-linear-gradient(to bottom, var(--accent) 0, var(--accent) 5px, transparent 5px, transparent 14px)',
      opacity: 0.45
    }} />
  );
}

// ══ FLAG CHIPS ════════════════════════════════════════
function Flag({ kind = "green", children }) {
  const colors = {
    green: { bg:'rgba(0,229,255,0.07)', color:'var(--accent)', border:'rgba(0,229,255,0.28)' },
    amber: { bg:'rgba(245,166,35,0.09)', color:'var(--amber)', border:'rgba(245,166,35,0.28)' },
    red:   { bg:'rgba(255,51,51,0.07)', color:'var(--red)',   border:'rgba(255,51,51,0.28)' },
    blue:  { bg:'rgba(64,180,255,0.07)',color:'var(--blue)',  border:'rgba(64,180,255,0.28)' }
  };
  const c = colors[kind] || colors.green;
  return (
    <span style={{
      fontFamily:"'DM Mono',monospace", fontSize:9,
      letterSpacing:'0.14em', textTransform:'uppercase',
      padding:'6px 10px', border:`2px solid ${c.border}`,
      background:c.bg, color:c.color, fontWeight:500
    }}>{children}</span>
  );
}

// ══ DIAG ROW ══════════════════════════════════════════
function DiagRow({ k, v, valueColor }) {
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'center',
      padding:'12px 16px', borderBottom:'1px solid var(--border)'
    }}>
      <span style={{
        fontFamily:"'DM Mono',monospace", fontSize:12,
        letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--muted)'
      }}>{k}</span>
      <span style={{
        fontFamily:"'DM Mono',monospace", fontSize:13,
        letterSpacing:'0.12em', color: valueColor || 'var(--accent)'
      }}>{v}</span>
    </div>
  );
}

// ══ STYLES ═══════════════════════════════════════════
const fbfStyles = {
  topBar: {
    height:54, flexShrink:0,
    display:'flex', alignItems:'center', justifyContent:'space-between',
    padding:'0 14px',
    background:'var(--panel)',
    borderBottom:'3px solid var(--accent)',
    position:'relative', zIndex:50,
    whiteSpace:'nowrap'
  },
  brand: { display:'flex', alignItems:'center', gap:10, cursor:'pointer', minWidth:0 },
  bMark: { display:'flex', flexDirection:'column', gap:3 },
  bm: { background:'var(--accent)', borderRadius:1 },
  bName: {
    fontFamily:"'Barlow Condensed',sans-serif",
    fontWeight:900, fontSize:17,
    letterSpacing:'0.16em', textTransform:'uppercase',
    color:'var(--text)', lineHeight:1
  },
  bSub: {
    fontFamily:"'DM Mono',monospace",
    fontSize:8, letterSpacing:'0.18em',
    textTransform:'uppercase', color:'var(--muted)', marginTop:2
  },
  topRight: { display:'flex', alignItems:'center', gap:8 },
  wakePill: {
    display:'flex', alignItems:'center', gap:5,
    fontFamily:"'DM Mono',monospace",
    fontSize:8, letterSpacing:'0.14em',
    textTransform:'uppercase', color:'var(--muted)'
  },
  wakeDot: {
    width:6, height:6, borderRadius:'50%',
    transition:'background 0.3s'
  },
  histBtn: {
    background:'var(--panel-2)', border:'2px solid var(--border-h)',
    padding:'8px 10px', cursor:'pointer',
    display:'flex', flexDirection:'column', gap:4, alignItems:'flex-end'
  },
  waveform: { display:'flex', alignItems:'center', gap:7, height:56, width:'100%' },
  micBtn: {
    width:'100%', height:96,
    background:'var(--accent)', border:'none', cursor:'pointer',
    display:'flex', alignItems:'center', justifyContent:'center', gap:18,
    position:'relative', overflow:'hidden'
  },
  micLabel: {
    fontFamily:"'Barlow Condensed',sans-serif",
    fontWeight:900, fontSize:28,
    letterSpacing:'0.18em', textTransform:'uppercase',
    color:'var(--black)', position:'relative', zIndex:1
  }
};

// Inject keyframes
if (!document.getElementById('fbf-keyframes')) {
  const style = document.createElement('style');
  style.id = 'fbf-keyframes';
  style.textContent = `
    @keyframes fbf-wv { 0%,100%{transform:scaleY(0.18);} 50%{transform:scaleY(1);} }
    @keyframes fbf-mpulse { 0%,100%{box-shadow:0 0 0 0 rgba(0,229,255,0);} 50%{box-shadow:0 0 0 10px rgba(0,229,255,0);} }
    @keyframes fbf-slosh { 0%,100%{transform:translateX(0);} 50%{transform:translateX(4px);} }
    @keyframes fbf-adot { 0%,100%{opacity:0.3;} 50%{opacity:1;} }
    @keyframes fbf-pulse { 0%,100%{opacity:1;} 50%{opacity:0.45;} }
    @keyframes fbf-shake { 0%,100%{transform:translateX(0);} 25%{transform:translateX(-3px);} 75%{transform:translateX(3px);} }
    @keyframes fbf-drip { 0%{transform:translateY(-8px);opacity:0;} 20%{opacity:1;} 100%{transform:translateY(14px);opacity:0;} }
    @keyframes fbf-scanline { 0%{transform:translateY(-100%);} 100%{transform:translateY(100%);} }
  `;
  document.head.appendChild(style);
}

Object.assign(window, {
  TopBar, Waveform, MicSlab, FluidMeter, SideRail, Flag, DiagRow, fbfStyles
});
