/* ===== BrewOS — CCT tank visual ===== */
const { useMemo } = React;

let _uidc = 0;
function useUid(){ return useMemo(()=> 'tk'+(_uidc++), []); }

// Bubble field for active fermentation
function Bubbles({ surfaceY, color, count }){
  const items = useMemo(()=>{
    const a=[];
    for(let i=0;i<count;i++){
      const x = 32 + Math.random()*56;
      const base = 160 - Math.random()*6;
      const rise = (surfaceY+6) - base;        // negative -> upward
      a.push({
        x, base,
        r: 0.7 + Math.random()*1.7,
        dur: 2.4 + Math.random()*3.2,
        delay: -Math.random()*5,
        rise,
      });
    }
    return a;
  // eslint-disable-next-line
  },[count, Math.round(surfaceY)]);
  return (
    <g>
      {items.map((b,i)=>(
        <circle key={i} cx={b.x} cy={b.base} r={b.r}
          fill="#fff" opacity="0"
          style={{
            ['--rise']: b.rise+'px',
            animation:`bubbleRise ${b.dur}s linear ${b.delay}s infinite`,
          }}/>
      ))}
    </g>
  );
}

/*
 props: state, fill(0..1), color, foam, glossy(bool), bubbles(bool), glow(bool)
*/
function Tank({ state='free', fill=0, color='#e6b13a', foam='#fbf2d2',
                glossy=true, bubbles=true, glow=true }){
  const uid = useUid();
  const stColor = (window.STATES[state]||{}).color || '#888';
  const hasLiquid = fill>0.001;
  const surfaceY = 168 - 124*fill;   // y of liquid surface
  const active = state==='ferment';
  const showGlow = glow && (state==='ferment'||state==='ready'||state==='cold');

  // interior path (clip for liquid + effects)
  const interior = "M28,40 L28,126 L60,168 L92,126 L92,40 Z";

  return (
    <svg viewBox="0 0 120 210" width="100%" style={{display:'block',overflow:'visible',
        filter: showGlow ? `drop-shadow(0 0 9px ${stColor}66)` : 'none'}}>
      <defs>
        <linearGradient id={uid+'-steel'} x1="0" y1="0" x2="1" y2="0">
          <stop offset="0"   stopColor="#23201c"/>
          <stop offset=".14" stopColor="#4d4842"/>
          <stop offset=".34" stopColor={glossy?'#6f6960':'#3e3a35'}/>
          <stop offset=".5"  stopColor="#3a3631"/>
          <stop offset=".72" stopColor="#2c2925"/>
          <stop offset="1"   stopColor="#1c1916"/>
        </linearGradient>
        <linearGradient id={uid+'-cone'} x1="0" y1="0" x2="1" y2="0">
          <stop offset="0"  stopColor="#1d1a17"/>
          <stop offset=".4" stopColor={glossy?'#5c574f':'#403c37'}/>
          <stop offset="1"  stopColor="#18150f"/>
        </linearGradient>
        <linearGradient id={uid+'-liq'} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0"  stopColor={color} stopOpacity=".95"/>
          <stop offset="1"  stopColor={color} stopOpacity="1"/>
        </linearGradient>
        <clipPath id={uid+'-in'}><path d={interior}/></clipPath>
      </defs>

      {/* ground shadow */}
      <ellipse cx="60" cy="201" rx="42" ry="5" fill="#000" opacity=".35"/>

      {/* legs */}
      <g stroke="#15110d" strokeWidth="3.4" strokeLinecap="round">
        <line x1="36" y1="150" x2="28" y2="196" stroke="#3a352f"/>
        <line x1="84" y1="150" x2="92" y2="196" stroke="#3a352f"/>
        <line x1="60" y1="160" x2="60" y2="197" stroke="#2f2b25"/>
      </g>
      <g fill="#26221d">
        <rect x="24.5" y="195" width="8" height="3" rx="1.5"/>
        <rect x="88" y="195" width="8" height="3" rx="1.5"/>
        <rect x="56.5" y="196" width="7" height="3" rx="1.5"/>
      </g>
      {/* support ring */}
      <line x1="30" y1="176" x2="90" y2="176" stroke="#2c2823" strokeWidth="2.2"/>

      {/* cone */}
      <path d="M24,128 L96,128 L61.5,170 L58.5,170 Z" fill={`url(#${uid}-cone)`} stroke="#15110d" strokeWidth="1"/>
      {/* outlet valve */}
      <rect x="57" y="168" width="6" height="9" rx="1.4" fill="#4a453e" stroke="#15110d" strokeWidth=".8"/>
      <circle cx="60" cy="178" r="3.1" fill="#5a544b" stroke="#15110d" strokeWidth=".8"/>
      <rect x="59" y="178" width="2" height="6" fill="#3a352f"/>

      {/* body */}
      <rect x="24" y="36" width="72" height="92" rx="3" fill={`url(#${uid}-steel)`} stroke="#15110d" strokeWidth="1"/>

      {/* ===== liquid + effects (clipped) ===== */}
      {hasLiquid && (
        <g clipPath={`url(#${uid}-in)`}>
          <rect x="24" y={surfaceY} width="72" height={172-surfaceY} fill={`url(#${uid}-liq)`}/>
          {/* inner shading on liquid */}
          <rect x="24" y={surfaceY} width="14" height={172-surfaceY} fill="#000" opacity=".16"/>
          <rect x="82" y={surfaceY} width="14" height={172-surfaceY} fill="#000" opacity=".22"/>
          {/* surface */}
          <ellipse cx="60" cy={surfaceY} rx="34" ry="3.4" fill={foam} opacity={state==='ferment'?'.9':'.6'}/>
          {/* krausen foam cap for fermenting */}
          {state==='ferment' && (
            <g opacity=".9">
              <ellipse cx="60" cy={surfaceY-1} rx="34" ry="4.2" fill={foam}/>
              <ellipse cx="48" cy={surfaceY-2} rx="9" ry="3" fill="#fff" opacity=".5"/>
              <ellipse cx="70" cy={surfaceY-1.5} rx="7" ry="2.6" fill="#fff" opacity=".4"/>
            </g>
          )}
          {active && bubbles && <Bubbles surfaceY={surfaceY} color={color} count={16}/>}
          {/* cold crash frost tint */}
          {state==='cold' && (
            <g>
              <rect x="24" y={surfaceY} width="72" height={172-surfaceY} fill="#bfe9f5" opacity=".14"/>
              {[...Array(10)].map((_,i)=>(
                <circle key={i} cx={30+Math.random()*60} cy={surfaceY+6+Math.random()*((170-surfaceY)*0.8)}
                  r={0.5+Math.random()*0.7} fill="#eaffff" opacity=".5"/>
              ))}
            </g>
          )}
        </g>
      )}

      {/* CIP spray swirl (empty) */}
      {state==='cip' && (
        <g clipPath={`url(#${uid}-in)`} opacity=".9">
          <g style={{transformOrigin:'60px 70px',animation:'cipSpin 1.6s linear infinite'}}>
            <circle cx="60" cy="70" r="15" fill="none" stroke={stColor} strokeWidth="1.4"
              strokeDasharray="3 6" opacity=".8"/>
            <circle cx="60" cy="70" r="8" fill="none" stroke={stColor} strokeWidth="1.2"
              strokeDasharray="2 5" opacity=".6"/>
          </g>
          {[...Array(7)].map((_,i)=>{
            const a=i/7*Math.PI*2;
            return <circle key={i} cx={60+Math.cos(a)*22} cy={64+Math.sin(a)*22} r="1.1" fill={stColor} opacity=".7"/>;
          })}
          <line x1="60" y1="44" x2="60" y2="58" stroke="#5a544b" strokeWidth="2.4"/>
        </g>
      )}

      {/* welded rings (over everything, subtle) */}
      <g stroke="#000" strokeOpacity=".28" strokeWidth=".8">
        {[50,64,78,92,106,120].map(y=>(<line key={y} x1="24.5" y1={y} x2="95.5" y2={y}/>))}
      </g>
      <g stroke="#fff" strokeOpacity=".05" strokeWidth=".8">
        {[51,65,79,93,107,121].map(y=>(<line key={y} x1="24.5" y1={y} x2="95.5" y2={y}/>))}
      </g>
      {/* gloss highlight */}
      {glossy && <rect x="33" y="37" width="7" height="90" rx="3" fill="#fff" opacity=".07"/>}

      {/* top manway / lid */}
      <ellipse cx="60" cy="36" rx="36" ry="6.5" fill="#211e1a" stroke="#15110d" strokeWidth="1"/>
      <ellipse cx="60" cy="34" rx="20" ry="5" fill="#2c2823" stroke="#15110d" strokeWidth="1"/>
      <ellipse cx="60" cy="32.5" rx="20" ry="4.2" fill="#13100c"/>
      <ellipse cx="60" cy="32" rx="14" ry="3" fill={hasLiquid?color:'#0c0a08'} opacity={hasLiquid?'.5':'1'}/>
      {/* side arm pipe */}
      <path d="M96,44 q14,2 14,20 l0,40" fill="none" stroke="#3a352f" strokeWidth="2.4" strokeLinecap="round"/>
      {/* thermowell pocket */}
      <circle cx="44" cy="100" r="2" fill="#4a453e" stroke="#15110d" strokeWidth=".6"/>
    </svg>
  );
}

Object.assign(window, { Tank });
