"use client"

import { useState } from "react"
import { motion } from "framer-motion"
import { useRevelationInView } from "@/lib/panel-reveal"
import { useLocale } from "next-intl"

type Cut = { key: string; y: number; fr: { name: string; sub?: string }; en: { name: string; sub?: string } }

// Les 8 produits finis de la SAR, du plus léger (haut) au plus lourd (bas) :
// Butane (sortie haute) → 6 produits latéraux → Fuel Oil (sortie basse).
const SIDE_CUTS: Cut[] = [
  { key: "essenceSuper",   y: 188, fr: { name: "Essence Super" },   en: { name: "Super gasoline" } },
  { key: "essencePirogue", y: 258, fr: { name: "Essence Pirogue" }, en: { name: "Pirogue gasoline" } },
  { key: "kerosene",       y: 328, fr: { name: "Kérosène" },        en: { name: "Kerosene" } },
  { key: "lampant",        y: 398, fr: { name: "Pétrole lampant" }, en: { name: "Lamp oil / Jet A-1" } },
  { key: "gasoil",         y: 468, fr: { name: "Gasoil" },          en: { name: "Gas oil" } },
  { key: "diesel",         y: 538, fr: { name: "Diesel Marine" },   en: { name: "Marine diesel" } },
]

const GREY = "#9aa3ab"
const ACTIVE = "#D97706"

export default function DistillationColumn({
  actif,
  onActif,
}: {
  // Pilotage optionnel : sans ces props, la colonne gere son survol seule.
  actif?: string | null
  onActif?: (cle: string | null) => void
} = {}) {
  const locale = useLocale()
  const isFr = locale !== "en"
  const [interne, setInterne] = useState<string | null>(null)
  const active = actif !== undefined ? actif : interne
  const setActive = (cle: string | null) => {
    setInterne(cle)
    onActif?.(cle)
  }
  const [ref, inView] = useRevelationInView({ triggerOnce: true, threshold: 0.2 })

  const RIGHT_X = 360 // bord droit de la colonne
  const LINE_END = 444
  const LABEL_X = 454

  const tapColor = (key: string) => (active === key ? ACTIVE : GREY)
  const nameFill = (key: string) => (active === key ? "#111827" : "#4b5563")

  const renderLabel = (key: string, x: number, y: number, name: string, sub?: string, anchor: "start" | "end" = "start") => (
    <>
      <text x={x} y={sub ? y - 4 : y + 5} textAnchor={anchor} fontSize="17"
            fontWeight={active === key ? 700 : 600} fill={nameFill(key)} className="transition-colors">
        {name}
      </text>
      {sub && (
        <text x={x} y={y + 13} textAnchor={anchor} fontSize="12.5" fill="#9ca3af">
          {sub}
        </text>
      )}
    </>
  )

  return (
    <div ref={ref} className="w-full">
      <motion.svg
        viewBox="0 40 680 645"
        className="w-full h-auto max-w-xl mx-auto block"
        role="img"
        aria-label={isFr ? "Colonne de distillation du pétrole brut et ses produits" : "Crude oil distillation column and its products"}
        initial={{ opacity: 0, y: 24 }}
        animate={inView ? { opacity: 1, y: 0 } : {}}
        transition={{ duration: 0.7, ease: [0.22, 1, 0.36, 1] }}
      >
        <defs>
          <linearGradient id="towerGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"   stopColor="#fbead0" />
            <stop offset="30%"  stopColor="#f0b429" />
            <stop offset="62%"  stopColor="#c9802f" />
            <stop offset="100%" stopColor="#5b3a1c" />
          </linearGradient>
        </defs>

        {/* ── Conduites (sous la colonne) ─────────────────────────────── */}
        {/* Butane (sortie haute) */}
        <g onMouseEnter={() => setActive("butane")} onMouseLeave={() => setActive(null)} style={{ cursor: "default" }}>
          <polyline points="290,112 290,64 432,64" fill="none" stroke={tapColor("butane")} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" className="transition-colors" />
          <circle cx="432" cy="64" r={active === "butane" ? 6 : 4} fill={tapColor("butane")} className="transition-all" />
          {renderLabel("butane", LABEL_X - 10, 64, "Butane", isFr ? "GPL" : "LPG")}
        </g>

        {/* Fuel Oil (sortie basse) */}
        <g onMouseEnter={() => setActive("fuelOil")} onMouseLeave={() => setActive(null)}>
          <polyline points="290,608 290,656 432,656" fill="none" stroke={tapColor("fuelOil")} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" className="transition-colors" />
          <circle cx="432" cy="656" r={active === "fuelOil" ? 6 : 4} fill={tapColor("fuelOil")} className="transition-all" />
          {renderLabel("fuelOil", LABEL_X - 10, 656, "Fuel Oil", isFr ? "industrie" : "industry")}
        </g>

        {/* Entrée pétrole brut (gauche, bas) */}
        <g onMouseEnter={() => setActive("brut")} onMouseLeave={() => setActive(null)}>
          <line x1="110" y1="556" x2="220" y2="556" stroke={tapColor("brut")} strokeWidth="3" strokeLinecap="round" className="transition-colors" />
          <circle cx="220" cy="556" r={active === "brut" ? 6 : 4} fill={tapColor("brut")} className="transition-all" />
          {renderLabel("brut", 100, 556, isFr ? "Pétrole brut" : "Crude oil", isFr ? "préchauffé" : "preheated", "end")}
        </g>

        {/* ── Corps de la colonne ─────────────────────────────────────── */}
        <rect x="220" y="110" width="140" height="500" rx="70" ry="70" fill="url(#towerGrad)" stroke="#c99a4e" strokeWidth="1.5" />

        {/* Températures */}
        <text x="290" y="152" textAnchor="middle" fontSize="16" fontWeight="700" fill="#6b4a1e">20°C</text>
        <text x="290" y="578" textAnchor="middle" fontSize="16" fontWeight="700" fill="#ffffff">400°C</text>

        {/* Texte process : la vapeur monte */}
        <text x="290" y="228" textAnchor="middle" fontSize="15.5" fill="#6b4a1e">{isFr ? "La vapeur" : "Vapor"}</text>
        <text x="290" y="247" textAnchor="middle" fontSize="15.5" fill="#6b4a1e">{isFr ? "monte" : "rises"}</text>

        {/* Flèche montante + chevrons animés */}
        <line x1="290" y1="440" x2="290" y2="300" stroke="#ffffff" strokeOpacity="0.55" strokeWidth="2" />
        <path d="M283 308 L290 298 L297 308" fill="none" stroke="#ffffff" strokeOpacity="0.8" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
        {inView && [0, 1, 2].map((i) => (
          <motion.path
            key={i}
            d="M283 0 L290 -10 L297 0"
            fill="none"
            stroke="#ffffff"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            initial={{ y: 432, opacity: 0 }}
            animate={{ y: [432, 312], opacity: [0, 0.9, 0] }}
            transition={{ duration: 2.4, repeat: Infinity, delay: i * 0.8, ease: "easeOut" }}
          />
        ))}

        {/* Texte process : les liquides descendent */}
        <text x="290" y="470" textAnchor="middle" fontSize="15.5" fill="#ffffff">{isFr ? "Les liquides" : "Liquids flow"}</text>
        <text x="290" y="489" textAnchor="middle" fontSize="15.5" fill="#ffffff">{isFr ? "descendent" : "down"}</text>

        {/* ── Soutirages latéraux (6 produits) ─────────────────────────── */}
        {SIDE_CUTS.map((cut, i) => {
          const label = isFr ? cut.fr : cut.en
          return (
            <motion.g
              key={cut.key}
              onMouseEnter={() => setActive(cut.key)}
              onMouseLeave={() => setActive(null)}
              style={{ cursor: "default" }}
              initial={{ opacity: 0, x: 12 }}
              animate={inView ? { opacity: 1, x: 0 } : {}}
              transition={{ duration: 0.45, delay: 0.25 + i * 0.1 }}
            >
              <line x1={RIGHT_X} y1={cut.y} x2={LINE_END} y2={cut.y} stroke={tapColor(cut.key)} strokeWidth="2.5" strokeLinecap="round" className="transition-colors" />
              <circle cx={RIGHT_X} cy={cut.y} r={active === cut.key ? 6 : 4} fill={tapColor(cut.key)} className="transition-all" />
              {renderLabel(cut.key, LABEL_X, cut.y, label.name, label.sub)}
            </motion.g>
          )
        })}
      </motion.svg>
    </div>
  )
}
