import { useState, useEffect } from "react";
import styles from "./Carconfigurator.module.scss";
import maincar from "../../assets/maincar.webp";
import imgRoof from "../../assets/roof.jpg";
import imgHood from "../../assets/hood.jpg";
import imgFloor from "../../assets/floor.jpg";
import imgDoor from "../../assets/door.jpg";
import imgTrunkLid from "../../assets/trunk_lid.jpg";
import imgTrunkFloor from "../../assets/trunk_flor.jpg";
import imgEngine from "../../assets/engine.jpg";
import imgArchInter from "../../assets/arch_inter_side.jpg";
import imgArchStreet from "../../assets/arch_street_side.jpg";
import imgPlasticFender from "../../assets/plastik_fender_liner_4.jpg";

// ─── Zone image map ───────────────────────────────────────────────────────────
const ZONE_IMAGES = {
  roof:          imgRoof,
  hood:          imgHood,
  floor:         imgFloor,
  doors:         imgDoor,
  trunk_lid:     imgTrunkLid,
  trunk_floor:   imgTrunkFloor,
  engine:        imgEngine,
  arch_interior: imgArchInter,
  arch_street:   imgArchStreet,
  fender_liner:  imgPlasticFender,
  wheel:         imgArchStreet,
};

const DOTS = [
  { id: "roof",          x: 44, y: 22 },
  { id: "trunk_lid",     x: 80, y: 27 },
  { id: "trunk_floor",   x: 68, y: 46 },
  { id: "arch_interior", x: 75, y: 43 },
  { id: "fender_liner",  x: 73, y: 51 },
  { id: "arch_street",   x: 47, y: 69 },
  { id: "engine",        x: 40, y: 59 },
  { id: "floor",         x: 58, y: 61 },
  { id: "doors",         x: 74, y: 80 },
  { id: "hood",          x: 17, y: 52 },
  { id: "wheel",         x: 42, y: 82 },
];

// ─── Product List ─────────────────────────────────────────────────────────────

function ProductList({ zone, pkg, bodyType, appData }) {
  if (!appData) return <p className={styles.emptyMsg}>Загрузка...</p>;

  const zoneInfo = appData.zones[zone];
  const products = zoneInfo?.products?.[bodyType]?.[pkg] || [];
  const total    = products.reduce((s, p) => s + p.price * p.qty, 0);
  const zoneImage = ZONE_IMAGES[zone];

  return (
    <div className={styles.productList}>
      {zoneImage ? (
        <div className={styles.zoneImageWrapper}>
          <img src={zoneImage} alt={zoneInfo?.label} className={styles.zoneImage} />
          <span className={styles.zoneImageLabel}>{zoneInfo?.label}</span>
        </div>
      ) : (
        <h3 className={styles.zoneTitle}>{zoneInfo?.label}</h3>
      )}

      {products.length === 0 && (
        <p className={styles.emptyMsg}>Нет товаров для данной зоны / пакета.</p>
      )}

      {products.map((p, i) => (
        <div key={i} className={styles.productRow}>
          <span className={styles.productName}>{p.name}</span>
          <span className={styles.productCalc}>
            <b>{p.price.toLocaleString("ru")} m</b>
            {" × "}
            {p.qty} {p.unit}
            {" = "}
            <b className={styles.subtotal}>
              {(p.price * p.qty).toLocaleString("ru")} m
            </b>
          </span>
        </div>
      ))}

      {products.length > 0 && (
        <div className={styles.totalRow}>
          Итого: <strong>{total.toLocaleString("ru")} m</strong>
        </div>
      )}

      {/* <div className={styles.actionButtons}>
        <button className={styles.btnBuy}>Купить</button>
        <button className={styles.btnView}>Смотреть</button>
      </div> */}
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function CarConfigurator() {
  const [appData,      setAppData]     = useState(null);
  const [selectedBody, setSelectedBody]= useState(null);
  const [selectedPkg,  setSelectedPkg] = useState(null);
  const [activeZone,   setActiveZone]  = useState("roof");
  const [tooltip,      setTooltip]     = useState(null);

  // Load data.json — served from /public/data.json, readable by all users
  useEffect(() => {
    fetch("/frontend-api/data")
      .then((r) => r.json())
      .then((data) => {
        setAppData(data);
        setSelectedBody(data.bodyTypes[0]?.id || "sedan");
        setSelectedPkg(data.packages[0] || "Максимум");
      })
      .catch(console.error);
  }, []);

  if (!appData) {
    return (
      <div className={styles.wrapper}>
        <p className={styles.emptyMsg}>Загрузка данных...</p>
      </div>
    );
  }

  return (
    <div className={styles.wrapper}>

      {/* ── Body Type Bar — TOP ──────────────────────────────── */}
      <div className={styles.bodyBar}>
        <p className={styles.sectionLabel}>Тип кузова</p>
        <div className={styles.bodyGrid}>
          {appData.bodyTypes.map((b) => (
            <button
              key={b.id}
              className={`${styles.bodyCard} ${selectedBody === b.id ? styles.active : ""}`}
              onClick={() => setSelectedBody(b.id)}
            >
              <span className={styles.bodyIcon}>
              {b.image ? <img src={b.image} alt={b.label} /> : b.icon}
            </span>
              <span className={styles.bodyLabel}>{b.label}</span>
              {selectedBody === b.id && <span className={styles.activeDot} />}
            </button>
          ))}
        </div>
      </div>

      {/* ── Main ─────────────────────────────────────────────── */}
      <div className={styles.main}>

        {/* Car visual */}
        <div className={styles.carWrapper}>
          <img
            className={styles.carImage}
            src={maincar}
            alt="Автомобиль"
            draggable={false}
          />

          {DOTS.map((dot) => (
            <button
              key={dot.id}
              className={`${styles.dot} ${activeZone === dot.id ? styles.dotActive : ""}`}
              style={{ left: `${dot.x}%`, top: `${dot.y}%` }}
              onClick={() => setActiveZone(dot.id)}
              onMouseEnter={() => setTooltip(dot)}
              onMouseLeave={() => setTooltip(null)}
              aria-label={appData.zones[dot.id]?.label}
            >
              <span className={styles.dotRipple} />
            </button>
          ))}

          {tooltip && (
            <div
              className={styles.tooltip}
              style={{ left: `${tooltip.x}%`, top: `${tooltip.y - 8}%` }}
            >
              {appData.zones[tooltip.id]?.label ?? tooltip.id}
            </div>
          )}
        </div>

        {/* Right panel */}
        <div className={styles.panel}>
          <div className={styles.pkgTabs}>
            {appData.packages.map((p) => (
              <button
                key={p}
                className={`${styles.pkgTab} ${selectedPkg === p ? styles.pkgActive : ""}`}
                onClick={() => setSelectedPkg(p)}
              >
                {p}
              </button>
            ))}
          </div>

          <div className={styles.productGridContainer}>
            <ProductList
              zone={activeZone}
              pkg={selectedPkg}
              bodyType={selectedBody}
              appData={appData}
            />
          </div>
        </div>
      </div>
    </div>
  );
}