/* PATTERNS OF INDIA — interactive fabric & textile swatches */
const { useState: fUseState, useEffect: fUseEffect, useRef: fUseRef, useId: fUseId } = React;

let __pid = 0;
const nextId = () => `pat-${++__pid}`;

/* ----- Individual fabric patterns. Each renders a tiled SVG <pattern>. ----- */
function PatternBandhani({ palette = ["#9d0d4a", "#fbf3e1", "#ef8c1a"] }) {
  const id = fUseRef(nextId()).current;
  return (
    <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice" viewBox="0 0 200 200">
      <defs>
        <pattern id={id} x="0" y="0" width="32" height="32" patternUnits="userSpaceOnUse">
          <rect width="32" height="32" fill={palette[0]} />
          {[[8, 8], [24, 8], [8, 24], [24, 24]].map(([x, y], i) => (
            <g key={i}>
              <circle cx={x} cy={y} r="3.2" fill={palette[1]} />
              <circle cx={x} cy={y} r="1.4" fill={palette[2]} />
            </g>
          ))}
          <circle cx="16" cy="16" r="2.2" fill={palette[1]} />
          <circle cx="16" cy="16" r="1" fill={palette[2]} />
        </pattern>
      </defs>
      <rect width="200" height="200" fill={`url(#${id})`} />
    </svg>
  );
}

function PatternBanarasi({ palette = ["#9d0d4a", "#c9a961", "#fbf3e1"] }) {
  const id = fUseRef(nextId()).current;
  return (
    <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice" viewBox="0 0 200 200">
      <defs>
        <pattern id={id} x="0" y="0" width="40" height="40" patternUnits="userSpaceOnUse">
          <rect width="40" height="40" fill={palette[0]} />
          {/* gold brocade diamond */}
          <path d="M 20,4 L 36,20 L 20,36 L 4,20 Z" fill="none" stroke={palette[1]} strokeWidth="1.4" />
          <path d="M 20,10 L 30,20 L 20,30 L 10,20 Z" fill={palette[1]} opacity=".5" />
          <circle cx="20" cy="20" r="3" fill={palette[1]} />
          <circle cx="20" cy="20" r="1.2" fill={palette[2]} />
          {/* tiny corner butis */}
          <circle cx="0" cy="0" r="1.4" fill={palette[1]} />
          <circle cx="40" cy="0" r="1.4" fill={palette[1]} />
          <circle cx="0" cy="40" r="1.4" fill={palette[1]} />
          <circle cx="40" cy="40" r="1.4" fill={palette[1]} />
        </pattern>
      </defs>
      <rect width="200" height="200" fill={`url(#${id})`} />
    </svg>
  );
}

function PatternIkat({ palette = ["#fbf3e1", "#06727d", "#9d0d4a"] }) {
  const id = fUseRef(nextId()).current;
  return (
    <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice" viewBox="0 0 200 200">
      <defs>
        <pattern id={id} x="0" y="0" width="40" height="40" patternUnits="userSpaceOnUse">
          <rect width="40" height="40" fill={palette[0]} />
          {/* zig-zag ikat */}
          <path d="M 0,10 L 10,0 L 20,10 L 30,0 L 40,10 M 0,30 L 10,20 L 20,30 L 30,20 L 40,30"
                fill="none" stroke={palette[1]} strokeWidth="2.4" strokeLinejoin="miter" />
          <path d="M 0,20 L 10,10 L 20,20 L 30,10 L 40,20 M 0,40 L 10,30 L 20,40 L 30,30 L 40,40"
                fill="none" stroke={palette[2]} strokeWidth="1.6" />
          {/* dots */}
          <circle cx="20" cy="5" r="1.4" fill={palette[2]} />
          <circle cx="20" cy="25" r="1.4" fill={palette[1]} />
        </pattern>
      </defs>
      <rect width="200" height="200" fill={`url(#${id})`} />
    </svg>
  );
}

function PatternPhulkari({ palette = ["#d7263d", "#ef8c1a", "#c9a961"] }) {
  const id = fUseRef(nextId()).current;
  return (
    <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice" viewBox="0 0 200 200">
      <defs>
        <pattern id={id} x="0" y="0" width="36" height="36" patternUnits="userSpaceOnUse">
          <rect width="36" height="36" fill={palette[0]} />
          {/* geometric flower */}
          {Array.from({ length: 8 }).map((_, i) => {
            const a = (i / 8) * Math.PI * 2;
            return <ellipse key={i}
                    cx={18 + Math.cos(a) * 8}
                    cy={18 + Math.sin(a) * 8}
                    rx="5" ry="2.6"
                    transform={`rotate(${a * 180 / Math.PI} ${18 + Math.cos(a) * 8} ${18 + Math.sin(a) * 8})`}
                    fill={palette[1]} />;
          })}
          <circle cx="18" cy="18" r="3" fill={palette[2]} />
          {/* corner accents */}
          <rect x="0" y="0" width="2" height="2" fill={palette[2]} />
          <rect x="34" y="34" width="2" height="2" fill={palette[2]} />
        </pattern>
      </defs>
      <rect width="200" height="200" fill={`url(#${id})`} />
    </svg>
  );
}

function PatternChanderi({ palette = ["#fbf3e1", "#c9a961", "#06727d"] }) {
  const id = fUseRef(nextId()).current;
  return (
    <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice" viewBox="0 0 200 200">
      <defs>
        <pattern id={id} x="0" y="0" width="24" height="24" patternUnits="userSpaceOnUse">
          <rect width="24" height="24" fill={palette[0]} />
          {/* sheer net grid */}
          <line x1="0" y1="12" x2="24" y2="12" stroke={palette[1]} strokeWidth=".7" />
          <line x1="12" y1="0" x2="12" y2="24" stroke={palette[1]} strokeWidth=".7" />
          {/* buti */}
          <g transform="translate(12,12)">
            <path d="M 0,-4 Q 3,-1 0,4 Q -3,-1 0,-4" fill={palette[2]} />
            <circle r="1" fill={palette[1]} />
          </g>
        </pattern>
      </defs>
      <rect width="200" height="200" fill={`url(#${id})`} />
    </svg>
  );
}

function PatternBlockPrint({ palette = ["#fbf3e1", "#9d0d4a", "#4a7c3a"] }) {
  const id = fUseRef(nextId()).current;
  return (
    <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice" viewBox="0 0 200 200">
      <defs>
        <pattern id={id} x="0" y="0" width="48" height="48" patternUnits="userSpaceOnUse">
          <rect width="48" height="48" fill={palette[0]} />
          {/* hand-stamped flower 1 */}
          <g transform="translate(12,12)">
            {Array.from({ length: 6 }).map((_, i) => {
              const a = (i / 6) * Math.PI * 2;
              return <ellipse key={i} cx={Math.cos(a) * 5} cy={Math.sin(a) * 5} rx="3.6" ry="2" fill={palette[1]}
                              transform={`rotate(${a * 180 / Math.PI} ${Math.cos(a) * 5} ${Math.sin(a) * 5})`} />;
            })}
            <circle r="2" fill={palette[2]} />
          </g>
          {/* hand-stamped flower 2 (offset) */}
          <g transform="translate(36,36)">
            {Array.from({ length: 6 }).map((_, i) => {
              const a = (i / 6) * Math.PI * 2;
              return <ellipse key={i} cx={Math.cos(a) * 5} cy={Math.sin(a) * 5} rx="3.6" ry="2" fill={palette[2]}
                              transform={`rotate(${a * 180 / Math.PI} ${Math.cos(a) * 5} ${Math.sin(a) * 5})`} />;
            })}
            <circle r="2" fill={palette[1]} />
          </g>
          {/* leaves */}
          <ellipse cx="36" cy="12" rx="3" ry="1.6" fill={palette[2]} transform="rotate(30 36 12)" />
          <ellipse cx="12" cy="36" rx="3" ry="1.6" fill={palette[2]} transform="rotate(-30 12 36)" />
        </pattern>
      </defs>
      <rect width="200" height="200" fill={`url(#${id})`} />
    </svg>
  );
}

function PatternPatola({ palette = ["#d7263d", "#fbf3e1", "#c9a961"] }) {
  const id = fUseRef(nextId()).current;
  return (
    <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice" viewBox="0 0 200 200">
      <defs>
        <pattern id={id} x="0" y="0" width="40" height="40" patternUnits="userSpaceOnUse">
          <rect width="40" height="40" fill={palette[0]} />
          {/* diamond geometric */}
          <path d="M 20,2 L 38,20 L 20,38 L 2,20 Z" fill={palette[1]} />
          <path d="M 20,8 L 32,20 L 20,32 L 8,20 Z" fill={palette[0]} />
          <path d="M 20,12 L 28,20 L 20,28 L 12,20 Z" fill={palette[2]} />
          <circle cx="20" cy="20" r="2" fill={palette[1]} />
          {/* corners */}
          <path d="M 0,0 L 4,0 L 0,4 Z" fill={palette[2]} />
          <path d="M 40,0 L 36,0 L 40,4 Z" fill={palette[2]} />
          <path d="M 0,40 L 4,40 L 0,36 Z" fill={palette[2]} />
          <path d="M 40,40 L 36,40 L 40,36 Z" fill={palette[2]} />
        </pattern>
      </defs>
      <rect width="200" height="200" fill={`url(#${id})`} />
    </svg>
  );
}

function PatternKantha({ palette = ["#fbf3e1", "#9d0d4a", "#06727d"] }) {
  const id = fUseRef(nextId()).current;
  return (
    <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice" viewBox="0 0 200 200">
      <defs>
        <pattern id={id} x="0" y="0" width="40" height="20" patternUnits="userSpaceOnUse">
          <rect width="40" height="20" fill={palette[0]} />
          {/* running-stitch lines */}
          {[5, 11, 17].map((y, r) => (
            <g key={r}>
              {Array.from({ length: 6 }).map((_, i) => (
                <line key={i} x1={i * 7 + (r * 2)} y1={y} x2={i * 7 + 4 + (r * 2)} y2={y}
                      stroke={r === 1 ? palette[2] : palette[1]} strokeWidth="1.2" strokeLinecap="round" />
              ))}
            </g>
          ))}
        </pattern>
      </defs>
      <rect width="200" height="200" fill={`url(#${id})`} />
    </svg>
  );
}

/* ---- The fabrics list with metadata ---- */
const FABRICS = [
  { id: "bandhani",   name: "Bandhani",     state: "Gujarat & Rajasthan", worn: "Mehendi · Haldi",
    note: "Tie-dyed in tiny dotted patterns by hand — bright, festive, joyful.",
    palette: ["#9d0d4a", "#fbf3e1", "#ef8c1a"], Comp: PatternBandhani },
  { id: "banarasi",   name: "Banarasi Brocade", state: "Uttar Pradesh", worn: "Wedding mandap",
    note: "Mughal-era silk woven with real zari (gold/silver thread). Heirloom-grade.",
    palette: ["#9d0d4a", "#c9a961", "#fbf3e1"], Comp: PatternBanarasi },
  { id: "ikat",       name: "Ikat",         state: "Telangana & Odisha", worn: "Sangeet",
    note: "Threads are tie-dyed before weaving — making the pattern \"blurred\" in the most precise way.",
    palette: ["#fbf3e1", "#06727d", "#9d0d4a"], Comp: PatternIkat },
  { id: "phulkari",   name: "Phulkari",     state: "Punjab", worn: "Sangeet",
    note: "Literally \"flower-work\" — silk-floss embroidered into geometric blooms by Punjabi women.",
    palette: ["#d7263d", "#ef8c1a", "#c9a961"], Comp: PatternPhulkari },
  { id: "chanderi",   name: "Chanderi",     state: "Madhya Pradesh", worn: "Reception",
    note: "Sheer cotton-silk with tiny butis — light enough to drift, royal enough to glow.",
    palette: ["#fbf3e1", "#c9a961", "#06727d"], Comp: PatternChanderi },
  { id: "blockprint", name: "Block Print",  state: "Rajasthan", worn: "Mehendi",
    note: "Hand-stamped on cotton using carved wooden blocks dipped in natural dyes.",
    palette: ["#fbf3e1", "#9d0d4a", "#4a7c3a"], Comp: PatternBlockPrint },
  { id: "patola",     name: "Patola",       state: "Gujarat", worn: "Pheras",
    note: "Double-ikat silk from Patan — said to take a family two years to weave one sari.",
    palette: ["#d7263d", "#fbf3e1", "#c9a961"], Comp: PatternPatola },
  { id: "kantha",     name: "Kantha",       state: "West Bengal", worn: "Haldi",
    note: "Old cotton saris layered and hand-stitched with running stitches into new heirlooms.",
    palette: ["#fbf3e1", "#9d0d4a", "#06727d"], Comp: PatternKantha },
];

/* ---- The section ---- */
function PatternsSection() {
  const [active, setActive] = fUseState(FABRICS[0]);
  const [transitioning, setTransitioning] = fUseState(false);

  const pick = (f) => {
    if (f.id === active.id) return;
    setTransitioning(true);
    setTimeout(() => {
      setActive(f);
      setTransitioning(false);
    }, 220);
  };

  const Comp = active.Comp;

  return (
    <section id="patterns" className="patterns" data-screen-label="04 Patterns">
      <div className="container">
        <div className="center">
          <div className="eyebrow">Patterns of India</div>
          <h2 className="section-title">Eight fabrics, eight stories</h2>
          <p className="section-sub">Each rasm has its own weave. Tap a swatch — the dupatta below changes.</p>
        </div>

        <div className="fabric-stage">
          <div className="dupatta-wrap">
            <div className={`dupatta ${transitioning ? "swap" : ""}`}>
              <Comp palette={active.palette} />
              {/* fringe top & bottom */}
              <div className="fringe top">
                {Array.from({ length: 28 }).map((_, i) =>
                  <span key={i} style={{ background: active.palette[1] }} />
                )}
              </div>
              <div className="fringe bottom">
                {Array.from({ length: 28 }).map((_, i) =>
                  <span key={i} style={{ background: active.palette[2] }} />
                )}
              </div>
            </div>
            <div className="dupatta-caption">
              <div className="cap-name">{active.name}</div>
              <div className="cap-meta">
                <span>📍 {active.state}</span>
                <span>•</span>
                <span>worn at {active.worn}</span>
              </div>
              <p className="cap-note">{active.note}</p>
            </div>
          </div>

          <div className="swatches">
            {FABRICS.map((f) => {
              const SwatchComp = f.Comp;
              const isActive = active.id === f.id;
              return (
                <button
                  key={f.id}
                  className={`swatch ${isActive ? "active" : ""}`}
                  onClick={() => pick(f)}
                  aria-label={f.name}
                >
                  <div className="sw-art">
                    <SwatchComp palette={f.palette} />
                  </div>
                  <div className="sw-label">{f.name}</div>
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- FabricDivider: a section-separating band that shows a traditional fabric.
   Tap to open a small modal with story. ---- */
const FABRIC_INFO = {
  bandhani:   { name: "Bandhani",         state: "Gujarat & Rajasthan", note: "Tie-dyed in tiny dotted patterns by hand — bright, festive, joyful.",                            palette: ["#9d0d4a","#fbf3e1","#ef8c1a"], Comp: PatternBandhani },
  banarasi:   { name: "Banarasi Brocade", state: "Uttar Pradesh",       note: "Mughal-era silk woven with real zari (gold/silver thread). Heirloom-grade.",                    palette: ["#9d0d4a","#c9a961","#fbf3e1"], Comp: PatternBanarasi },
  ikat:       { name: "Ikat",             state: "Telangana & Odisha",  note: "Threads are tie-dyed before weaving — the pattern is precisely \"blurred\".",                   palette: ["#fbf3e1","#06727d","#9d0d4a"], Comp: PatternIkat },
  phulkari:   { name: "Phulkari",         state: "Punjab",              note: "Literally \"flower-work\" — silk-floss embroidered into geometric blooms by Punjabi women.",     palette: ["#d7263d","#ef8c1a","#c9a961"], Comp: PatternPhulkari },
  chanderi:   { name: "Chanderi",         state: "Madhya Pradesh",      note: "Sheer cotton-silk with tiny butis — light enough to drift, royal enough to glow.",              palette: ["#fbf3e1","#c9a961","#06727d"], Comp: PatternChanderi },
  blockprint: { name: "Block Print",      state: "Rajasthan",           note: "Hand-stamped on cotton using carved wooden blocks dipped in natural dyes.",                     palette: ["#fbf3e1","#9d0d4a","#4a7c3a"], Comp: PatternBlockPrint },
  patola:     { name: "Patola",           state: "Gujarat",             note: "Double-ikat silk from Patan — said to take a family two years to weave one sari.",              palette: ["#d7263d","#fbf3e1","#c9a961"], Comp: PatternPatola },
  kantha:     { name: "Kantha",           state: "West Bengal",         note: "Old saris layered and hand-stitched with running stitches into new heirlooms.",                 palette: ["#fbf3e1","#9d0d4a","#06727d"], Comp: PatternKantha },
};

function FabricDivider({ kind, onOpen }) {
  const f = FABRIC_INFO[kind];
  if (!f) return null;
  const C = f.Comp;
  return (
    <button className="fabric-divider" onClick={() => onOpen(kind)} aria-label={`About ${f.name}`}>
      <div className="fd-pattern" aria-hidden="true">
        <C palette={f.palette} />
      </div>
    </button>
  );
}

function FabricModal({ kind, onClose }) {
  const f = FABRIC_INFO[kind];
  aUseEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);
  if (!f) return null;
  const C = f.Comp;
  return (
    <div className="art-modal" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="art-modal-card" style={{ borderTop: `6px solid ${f.palette[0]}` }}>
        <button className="close" onClick={onClose} aria-label="close">✕</button>
        <div className="amc-left" style={{ background: f.palette[0], padding: 0, minHeight: 280, overflow: "hidden" }}>
          <div style={{ width: "100%", height: "100%", minHeight: 280 }}>
            <C palette={f.palette} />
          </div>
        </div>
        <div className="amc-right">
          <div className="amc-eyebrow">
            <span className="dot" style={{ background: f.palette[0] }} />
            Fabric of India
          </div>
          <h3>{f.name}</h3>
          <div className="amc-art-meta">
            <span className="amc-state">{f.state}</span>
          </div>
          <p className="amc-art-note">{f.note}</p>
        </div>
      </div>
    </div>
  );
}

window.FabricDivider = FabricDivider;
window.FabricModal = FabricModal;
