/* ============================================================
   JIT BATCH — Schema impianto animato (SVG)
   Silos, tramogge, nastro, mescolatore, autobetoniera con
   livelli live + flusso materiali reattivo alla fase di ciclo.
   Exposes window.PlantSchema
   phase: idle | aggregati | cemento | acqua | miscelazione | scarico | completato
   ============================================================ */
const { useEffect: usePE, useState: usePS, useRef: usePR } = React;

const MAT_COL = {
  cemento: "#C7CCD3", cemento2: "#AEB4BD",
  acqua: "#5BA7D6", additivo: "#F2A23E",
  sabbia: "#D9BD8C", ghiaiaF: "#B4ADA1", ghiaiaG: "#938D81",
  cls: "#8E949C", clsWet: "#7E848C",
};
const REDUCE = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

function lvColor(pct) {
  if (pct <= 15) return "var(--status-alarm)";
  if (pct <= 30) return "var(--status-warn)";
  return "var(--status-run)";
}

/* material pellets travelling along a pipe path (SMIL motion) */
function Flow({ d, color, active, count = 5, dur = 1.0, r = 2.7 }) {
  if (!active || REDUCE) return null;
  return (
    <g>
      {Array.from({ length: count }).map((_, i) => (
        <circle key={i} r={r} fill={color}>
          <animateMotion dur={`${dur}s`} repeatCount="indefinite" begin={`${(-(i * dur) / count).toFixed(2)}s`} path={d} calcMode="linear" />
        </circle>
      ))}
    </g>
  );
}

function PlantSchema({ phase = "idle", levels = {}, auto = false, height = 440 }) {
  const AUTO_SEQ = ["aggregati", "cemento", "acqua", "miscelazione", "scarico", "idle"];
  const [autoPhase, setAutoPhase] = usePS("aggregati");
  usePE(() => {
    if (!auto) return;
    let i = 0;
    const t = setInterval(() => { i = (i + 1) % AUTO_SEQ.length; setAutoPhase(AUTO_SEQ[i]); }, 2800);
    return () => clearInterval(t);
  }, [auto]);
  const ph = auto ? autoPhase : phase;

  const L = (id, def) => (levels[id] != null ? levels[id] : def);
  const act = {
    agg: ph === "aggregati", cem: ph === "cemento", water: ph === "acqua",
    mix: ph === "miscelazione", disc: ph === "scarico",
  };
  const anyDose = act.agg || act.cem || act.water;

  // mixer fill fraction by phase (0..1 of interior)
  const mixFrac = { idle: 0.0, aggregati: 0.42, cemento: 0.62, acqua: 0.82, miscelazione: 0.84, scarico: 0.06, completato: 0.0 }[ph] ?? 0;
  const truckFrac = act.disc ? 0.74 : 0.05;

  const fillRect = (x, yTop, yBot, w, pct, color, clip) => {
    const h = (yBot - yTop) * (pct / 100);
    return <rect x={x} y={yBot - h} width={w} height={h} fill={color} clipPath={`url(#${clip})`} style={{ transition: "y 700ms cubic-bezier(0.2,0,0,1), height 700ms cubic-bezier(0.2,0,0,1)" }} />;
  };

  const Pipe = ({ d, active, color, count, dur }) => (
    <g>
      <path d={d} fill="none" stroke="var(--border-strong)" strokeWidth="6.5" strokeLinecap="round" strokeLinejoin="round" opacity="0.45" />
      {active && <path d={d} className="ps-flow" fill="none" stroke={color} strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="2 10" opacity="0.55" />}
      <Flow d={d} color={color} active={active} count={count} dur={dur} />
    </g>
  );

  const dotFor = (pct, activeGlow) => (
    <g>{activeGlow && <circle r="9" fill="var(--jit-orange)" opacity="0.25" className="ps-pulse" />}<circle r="4.5" fill={lvColor(pct)} /></g>
  );

  const cem1 = L("S1", 60), cem2 = L("S2", 23), water = L("VA", 73), addi = L("AD", 64);
  const sab = L("TS", 66), gf = L("TF", 49), gg = L("TG", 19);

  // mixer interior region
  const MIX_X = 416, MIX_W = 108, MIX_TOP = 340, MIX_BOT = 390;
  const mixH = (MIX_BOT - MIX_TOP) * mixFrac;
  const mixY = MIX_BOT - mixH;

  return (
    <div style={{ width: "100%", position: "relative" }}>
      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes psflow { to { stroke-dashoffset: -48; } }
        .ps-flow { animation: psflow 0.6s linear infinite; }
        @keyframes psspin { to { transform: rotate(360deg); } }
        .ps-blades { transform-origin: 470px 366px; animation: psspin 1.0s linear infinite; }
        .ps-blades.slow { animation-duration: 6s; }
        @keyframes psribs { to { transform: translateX(-26px); } }
        .ps-ribs { animation: psribs 1.5s linear infinite; }
        .ps-ribs.fast { animation-duration: 0.5s; }
        @keyframes psbelt { to { stroke-dashoffset: -28; } }
        .ps-belt { animation: psbelt 0.55s linear infinite; }
        @keyframes pspulse { 0%,100% { opacity: 1; } 50% { opacity: 0.35; } }
        .ps-active-label { animation: pspulse 1.4s ease-in-out infinite; }
        @keyframes psp2 { 0%,100% { transform: scale(0.7); opacity: 0.45; } 50% { transform: scale(1.25); opacity: 0.12; } }
        .ps-pulse { animation: psp2 1.3s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
        @keyframes pschurn { 0% { transform: translateX(-14px); } 50% { transform: translateX(14px); } 100% { transform: translateX(-14px); } }
        .ps-churn { animation: pschurn 0.9s ease-in-out infinite; }
        @keyframes psglow { 0%,100% { opacity: 0.9; } 50% { opacity: 0.35; } }
        .ps-glow { animation: psglow 1.2s ease-in-out infinite; }
        @keyframes psrise { from { opacity:0; } to { opacity:1; } }
        @media (prefers-reduced-motion: reduce) {
          .ps-flow,.ps-blades,.ps-ribs,.ps-belt,.ps-active-label,.ps-pulse,.ps-churn,.ps-glow { animation: none !important; }
        }
      `}} />
      <svg viewBox="0 0 920 536" preserveAspectRatio="xMidYMid meet" style={{ width: "100%", height: height, display: "block" }}>
        <defs>
          <clipPath id="cl-s1"><path d="M70 70h80v150l-40 34-40-34z" /></clipPath>
          <clipPath id="cl-s2"><path d="M180 70h80v150l-40 34-40-34z" /></clipPath>
          <clipPath id="cl-wa"><rect x="300" y="120" width="58" height="120" rx="5" /></clipPath>
          <clipPath id="cl-ad"><rect x="378" y="135" width="42" height="105" rx="5" /></clipPath>
          <clipPath id="cl-ts"><path d="M470 80h120l-22 150h-76z" /></clipPath>
          <clipPath id="cl-tf"><path d="M600 80h120l-22 150h-76z" /></clipPath>
          <clipPath id="cl-tg"><path d="M730 80h120l-22 150h-76z" /></clipPath>
          <clipPath id="cl-mix"><rect x={MIX_X} y={MIX_TOP} width={MIX_W} height={MIX_BOT - MIX_TOP} rx="6" /></clipPath>
          <clipPath id="cl-drum2"><path d="M -76 -8 C -60 -32 -20 -37 16 -37 C 50 -37 72 -24 80 -6 C 84 -2 84 2 80 6 C 72 24 50 37 16 37 C -20 37 -60 32 -76 8 C -82 4 -82 -4 -76 -8 Z" /></clipPath>
          <linearGradient id="ps-metal" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="#EDF1F6" /><stop offset="50%" stopColor="#FCFDFE" /><stop offset="100%" stopColor="#DCE3EC" />
          </linearGradient>
        </defs>

        {/* support structure */}
        <g stroke="var(--border-strong)" strokeWidth="3" opacity="0.5" strokeLinecap="round">
          <line x1="60" y1="452" x2="486" y2="452" strokeWidth="4" />
          <line x1="486" y1="452" x2="486" y2="508" strokeWidth="3" />
          <line x1="486" y1="508" x2="900" y2="508" strokeWidth="4" />
          <line x1="110" y1="255" x2="110" y2="452" /><line x1="220" y1="255" x2="220" y2="452" />
          <line x1="528" y1="232" x2="528" y2="300" /><line x1="658" y1="232" x2="658" y2="300" />
          <line x1="788" y1="232" x2="788" y2="300" />
        </g>

        {/* ===== Header manifold (sources -> mixer) ===== */}
        <Pipe d="M110 255 V300 H470 V322" active={act.cem} color={MAT_COL.cemento} count={6} dur={1.1} />
        <Pipe d="M220 255 V300 H470" active={act.cem} color={MAT_COL.cemento2} count={5} dur={1.0} />
        <Pipe d="M329 240 V300 H470" active={act.water} color={MAT_COL.acqua} count={6} dur={0.85} />
        <Pipe d="M399 240 V300 H470" active={act.water} color={MAT_COL.additivo} count={4} dur={0.9} />

        {/* ===== Cement silo 1 ===== */}
        <g>
          <ellipse cx="110" cy="70" rx="40" ry="10" fill="url(#ps-metal)" stroke="var(--border-strong)" strokeWidth="1.5" />
          <path d="M70 70h80v150l-40 34-40-34z" fill="url(#ps-metal)" stroke="var(--border-strong)" strokeWidth="1.5" />
          {fillRect(70, 70, 254, 80, cem1, MAT_COL.cemento, "cl-s1")}
          <path d="M70 70h80v150l-40 34-40-34z" fill="none" stroke={act.cem ? "var(--jit-orange)" : "var(--border-strong)"} strokeWidth={act.cem ? 2.5 : 1.5} className={act.cem ? "ps-glow" : ""} />
          <g transform="translate(138 60)">{dotFor(cem1, act.cem)}</g>
          <text x="110" y="150" textAnchor="middle" style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 15, fill: "var(--navy-900)" }}>{cem1}%</text>
        </g>
        {/* ===== Cement silo 2 ===== */}
        <g>
          <ellipse cx="220" cy="70" rx="40" ry="10" fill="url(#ps-metal)" stroke="var(--border-strong)" strokeWidth="1.5" />
          <path d="M180 70h80v150l-40 34-40-34z" fill="url(#ps-metal)" stroke="var(--border-strong)" strokeWidth="1.5" />
          {fillRect(180, 70, 254, 80, cem2, MAT_COL.cemento2, "cl-s2")}
          <path d="M180 70h80v150l-40 34-40-34z" fill="none" stroke={act.cem ? "var(--jit-orange)" : "var(--border-strong)"} strokeWidth={act.cem ? 2.5 : 1.5} className={act.cem ? "ps-glow" : ""} />
          <g transform="translate(248 60)">{dotFor(cem2, act.cem)}</g>
          <text x="220" y="150" textAnchor="middle" style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 15, fill: "var(--navy-900)" }}>{cem2}%</text>
        </g>

        {/* ===== Water tank ===== */}
        <g>
          <rect x="300" y="120" width="58" height="120" rx="5" fill="#EAF3FA" stroke="var(--border-strong)" strokeWidth="1.5" />
          {fillRect(300, 120, 240, 58, water, MAT_COL.acqua, "cl-wa")}
          <rect x="300" y="120" width="58" height="120" rx="5" fill="none" stroke={act.water ? "var(--jit-orange)" : "var(--border-strong)"} strokeWidth={act.water ? 2.5 : 1.5} className={act.water ? "ps-glow" : ""} />
          <g transform="translate(348 112)">{dotFor(water, act.water)}</g>
          <text x="329" y="185" textAnchor="middle" style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 13, fill: "#0E4A73" }}>{water}%</text>
        </g>
        {/* ===== Additive tank ===== */}
        <g>
          <rect x="378" y="135" width="42" height="105" rx="5" fill="#FDF3E5" stroke="var(--border-strong)" strokeWidth="1.5" />
          {(() => { const h = (240 - 135) * (addi / 100); return <rect x="378" y={240 - h} width="42" height={h} fill={MAT_COL.additivo} clipPath="url(#cl-ad)" style={{ transition: "y 700ms, height 700ms" }} />; })()}
          <rect x="378" y="135" width="42" height="105" rx="5" fill="none" stroke={act.water ? "var(--jit-orange)" : "var(--border-strong)"} strokeWidth={act.water ? 2.5 : 1.5} className={act.water ? "ps-glow" : ""} />
          <g transform="translate(410 127)">{dotFor(addi, act.water)}</g>
          <text x="399" y="192" textAnchor="middle" style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 12, fill: "#8a5410" }}>{addi}%</text>
        </g>

        {/* ===== Aggregate hoppers ===== */}
        {[{ x: 470, clip: "cl-ts", col: MAT_COL.sabbia, pct: sab, lbl: "SABBIA" },
          { x: 600, clip: "cl-tf", col: MAT_COL.ghiaiaF, pct: gf, lbl: "GH 4/12" },
          { x: 730, clip: "cl-tg", col: MAT_COL.ghiaiaG, pct: gg, lbl: "GH 12/20" }].map((h, i) => {
          const beltY = 300 - ((h.x + 60 - 500) / 300) * 48;
          return (
          <g key={i}>
            {/* drop from hopper outlet to belt */}
            <Pipe d={`M${h.x + 60} 230 V${beltY.toFixed(0)}`} active={act.agg} color={h.col} count={3} dur={0.7} />
            <path d={`M${h.x} 80h120l-22 150h-76z`} fill="#F1F4F8" stroke="var(--border-strong)" strokeWidth="1.5" />
            {(() => { const top = 80, bot = 230; const fh = (bot - top) * (h.pct / 100); return <rect x={h.x} y={bot - fh} width="120" height={fh} fill={h.col} clipPath={`url(#${h.clip})`} style={{ transition: "y 700ms, height 700ms" }} />; })()}
            <path d={`M${h.x} 80h120l-22 150h-76z`} fill="none" stroke={act.agg ? "var(--jit-orange)" : "var(--border-strong)"} strokeWidth={act.agg ? 2.5 : 1.5} className={act.agg ? "ps-glow" : ""} />
            <line x1={h.x} y1="80" x2={h.x + 120} y2="80" stroke="var(--border-strong)" strokeWidth="2" />
            <g transform={`translate(${h.x + 108} 72)`}>{dotFor(h.pct, act.agg)}</g>
            <text x={h.x + 60} y="160" textAnchor="middle" style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 15, fill: "var(--navy-900)" }}>{h.pct}%</text>
            <text x={h.x + 60} y="100" textAnchor="middle" style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 10.5, fill: "var(--navy-700)", letterSpacing: "0.05em" }}>{h.lbl}</text>
          </g>
        );})}

        {/* ===== Conveyor belt (hoppers -> mixer) ===== */}
        <g>
          <line x1="500" y1="300" x2="800" y2="252" stroke="var(--gray-400)" strokeWidth="15" strokeLinecap="round" />
          <line x1="500" y1="300" x2="800" y2="252" stroke="var(--gray-200)" strokeWidth="10" strokeLinecap="round" />
          {/* moving belt texture */}
          <line x1="500" y1="300" x2="800" y2="252" stroke="var(--gray-400)" strokeWidth="10" strokeLinecap="butt" strokeDasharray="3 11" className={act.agg ? "ps-belt" : ""} opacity="0.6" />
          <circle cx="500" cy="300" r="12" fill="var(--bg-surface)" stroke="var(--gray-500)" strokeWidth="2.5" />
          <circle cx="800" cy="252" r="12" fill="var(--bg-surface)" stroke="var(--gray-500)" strokeWidth="2.5" />
          {/* aggregate lumps riding the belt */}
          {act.agg && !REDUCE && [0, 1, 2, 3, 4].map(i => (
            <g key={i}>
              <ellipse rx="6" ry="3.4" fill={[MAT_COL.sabbia, MAT_COL.ghiaiaF, MAT_COL.ghiaiaG][i % 3]} stroke="rgba(0,0,0,0.08)" strokeWidth="0.5">
                <animateMotion dur="1.5s" repeatCount="indefinite" begin={`${(-(i * 1.5) / 5).toFixed(2)}s`} path="M800 246 L500 294" calcMode="linear" />
              </ellipse>
            </g>
          ))}
          {/* belt -> mixer drop */}
          <Pipe d="M500 300 V322" active={act.agg} color={MAT_COL.sabbia} count={3} dur={0.55} />
        </g>

        {/* ===== Mixer ===== */}
        <g>
          <rect x="410" y="322" width="120" height="72" rx="10" fill="#E7ECF2" stroke="var(--navy-700)" strokeWidth="2.5" />
          {/* dynamic concrete fill */}
          <rect x={MIX_X} y={mixY} width={MIX_W} height={mixH} fill={act.mix ? MAT_COL.clsWet : MAT_COL.cls} clipPath="url(#cl-mix)" style={{ transition: "y 800ms cubic-bezier(0.2,0,0,1), height 800ms cubic-bezier(0.2,0,0,1), fill 400ms" }} />
          {/* churn waves during mixing */}
          {act.mix && !REDUCE && (
            <g clipPath="url(#cl-mix)">
              <ellipse cx="470" cy={mixY + 4} rx="34" ry="7" fill="rgba(255,255,255,0.18)" className="ps-churn" />
              <ellipse cx="470" cy={mixY + 12} rx="40" ry="8" fill="rgba(0,0,0,0.07)" className="ps-churn" style={{ animationDelay: "-0.45s" }} />
            </g>
          )}
          <rect x="410" y="322" width="120" height="14" rx="7" fill="var(--navy-700)" />
          {/* blades */}
          <g className={`ps-blades ${act.mix ? "" : "slow"}`} style={{ opacity: 0.92 }}>
            <line x1="470" y1="350" x2="470" y2="384" stroke="var(--navy-800)" strokeWidth="3" />
            <line x1="450" y1="367" x2="490" y2="367" stroke="var(--navy-800)" strokeWidth="3" />
            <circle cx="470" cy="367" r="5" fill="var(--navy-800)" />
          </g>
          <rect x="410" y="322" width="120" height="72" rx="10" fill="none" stroke={act.mix ? "var(--jit-orange)" : "var(--navy-700)"} strokeWidth={act.mix ? 3 : 2.5} className={act.mix ? "ps-glow" : ""} />
          <text x="470" y="412" textAnchor="middle" style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 11, fill: "var(--navy-700)", letterSpacing: "0.06em" }}>MESCOLATORE</text>
          {/* discharge chute to truck */}
          <Pipe d="M528 388 L560 399 L603 397" active={act.disc} color={MAT_COL.clsWet} count={6} dur={0.7} />
        </g>

        {/* ===== Autobetoniera ===== */}
        <g transform="translate(540 372)">
          {/* chassis frame */}
          <rect x="38" y="92" width="258" height="15" rx="4" fill="var(--navy-800)" />
          <rect x="38" y="92" width="258" height="4" fill="var(--navy-500)" opacity="0.7" />
          {/* drum cradle + support rollers */}
          <path d="M104 92 L126 60 M198 92 L178 60" stroke="var(--navy-700)" strokeWidth="5" strokeLinecap="round" />
          <circle cx="126" cy="58" r="6" fill="var(--bg-surface)" stroke="var(--navy-700)" strokeWidth="2.5" />
          <circle cx="178" cy="58" r="6" fill="var(--bg-surface)" stroke="var(--navy-700)" strokeWidth="2.5" />
          {/* wheels (tandem rear + steer under cab) */}
          {[100, 138, 258].map((cx, i) => (
            <g key={i}>
              <circle cx={cx} cy="116" r="16" fill="#222A35" stroke="var(--gray-700)" strokeWidth="3" />
              <circle cx={cx} cy="116" r="6" fill="var(--gray-500)" />
            </g>
          ))}
          {/* cab (right) */}
          <path d="M236 96 V58 a6 6 0 0 1 6 -6 h30 l16 22 v22 z" fill="var(--jit-orange)" stroke="var(--orange-700)" strokeWidth="1.5" />
          <path d="M247 56 h21 l12 16 h-33 z" fill="#C6E4F4" stroke="var(--orange-700)" strokeWidth="1.2" />
          <rect x="289" y="82" width="5" height="10" rx="1" fill="#FCE9A6" stroke="var(--orange-700)" strokeWidth="0.8" />
          <line x1="234" y1="66" x2="225" y2="66" stroke="var(--navy-800)" strokeWidth="2.5" strokeLinecap="round" />
          {/* ===== mixing drum ===== */}
          <g transform="translate(150 52) rotate(-8)">
            <path d="M -76 -8 C -60 -32 -20 -37 16 -37 C 50 -37 72 -24 80 -6 C 84 -2 84 2 80 6 C 72 24 50 37 16 37 C -20 37 -60 32 -76 8 C -82 4 -82 -4 -76 -8 Z" fill="url(#ps-metal)" stroke="var(--navy-700)" strokeWidth="2.5" />
            {/* concrete load */}
            {(() => { const fh = 74 * truckFrac; return <rect x="-82" y={37 - fh} width="166" height={fh} fill={MAT_COL.clsWet} clipPath="url(#cl-drum2)" style={{ transition: "y 1400ms cubic-bezier(0.2,0,0,1), height 1400ms cubic-bezier(0.2,0,0,1)" }} />; })()}
            {/* helical mixing ribs */}
            <g clipPath="url(#cl-drum2)">
              <g className={`ps-ribs ${act.disc ? "fast" : ""}`}>
                {[-78, -52, -26, 0, 26, 52, 78, 104].map((x, i) => (
                  <path key={i} d={`M ${x} -37 C ${x - 7} -12 ${x - 7} 12 ${x - 15} 37`} fill="none" stroke="var(--navy-600)" strokeWidth="4" opacity="0.4" />
                ))}
              </g>
            </g>
            {/* front cap (right, cab side) */}
            <ellipse cx="79" cy="0" rx="6" ry="20" fill="var(--navy-700)" opacity="0.85" />
            {/* charging funnel (left, toward plant) */}
            <path d="M -74 -12 L -102 -40 L -68 -40 L -70 12 Z" fill="var(--gray-200)" stroke="var(--navy-700)" strokeWidth="1.8" strokeLinejoin="round" />
            <line x1="-102" y1="-40" x2="-68" y2="-40" stroke="var(--navy-700)" strokeWidth="3" strokeLinecap="round" />
            {/* outline + active glow */}
            <path d="M -76 -8 C -60 -32 -20 -37 16 -37 C 50 -37 72 -24 80 -6 C 84 -2 84 2 80 6 C 72 24 50 37 16 37 C -20 37 -60 32 -76 8 C -82 4 -82 -4 -76 -8 Z" fill="none" stroke={act.disc ? "var(--jit-orange)" : "var(--navy-700)"} strokeWidth={act.disc ? 3 : 2.5} className={act.disc ? "ps-glow" : ""} />
          </g>
          <text x="170" y="152" textAnchor="middle" style={{ fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 11, fill: "var(--fg-3)" }}>GH 482 KP · 9 m³</text>
        </g>

        {/* phase ribbon */}
        {ph !== "idle" && ph !== "completato" && (
          <g className="ps-active-label">
            <circle cx="80" cy="494" r="5" fill="var(--jit-orange)" />
            <text x="92" y="498" style={{ fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 13, fill: "var(--fg-accent)", letterSpacing: "0.04em" }}>
              {{ aggregati: "DOSAGGIO AGGREGATI", cemento: "DOSAGGIO CEMENTO", acqua: "DOSAGGIO ACQUA + ADDITIVI", miscelazione: "MISCELAZIONE IN CORSO", scarico: "SCARICO SU AUTOBETONIERA" }[ph]}
            </text>
          </g>
        )}
      </svg>
    </div>
  );
}
window.PlantSchema = PlantSchema;
