/* global React, ReactDOM */
const { useState, useEffect, useMemo } = React;

const BRAND  = '#5C3A1E';
const SELECT = 'w-full border border-gray-300 rounded-lg px-3 py-2.5 text-base bg-white text-gray-800 focus:outline-none focus:ring-1 focus:ring-amber-700 focus:border-amber-700 transition-colors';

/* ─────────────────────────── DATA ─────────────────────────── */

const WOODS = {
  maple: {
    id: 'maple', label: 'Maple',
    base: '#F0D898', mid: '#D4B660', shadow: '#A88828', edge: '#7A6010',
    grainGap: 6.5, grainOp: 0.30,
    desc: 'Tight, fine grain. Bright, crisp tonal quality.'
  },
  walnut: {
    id: 'walnut', label: 'Walnut',
    base: '#7D4A28', mid: '#5C3018', shadow: '#3C1E0C', edge: '#241008',
    grainGap: 9, grainOp: 0.48,
    desc: 'Rich dark hardwood. Deep, resonant sustain.'
  },
  poplar: {
    id: 'poplar', label: 'Poplar',
    base: '#C0C870', mid: '#A0A850', shadow: '#808840', edge: '#606830',
    grainGap: 5.5, grainOp: 0.26,
    desc: 'Lightweight with distinctive green-streaked figure.'
  },
  sycamore: {
    id: 'sycamore', label: 'Sycamore',
    base: '#D4B87C', mid: '#B89A58', shadow: '#98804A', edge: '#786038',
    grainGap: 6.2, grainOp: 0.36,
    desc: 'Distinctive lace figure. Warm, balanced character.'
  },
  cherry: {
    id: 'cherry', label: 'Cherry',
    base: '#A84038', mid: '#8C3028', shadow: '#601814', edge: '#400C0A',
    grainGap: 5, grainOp: 0.38,
    desc: 'Warm reddish tones that deepen and age over time.'
  },
  purpleHeart: {
    id: 'purpleHeart', label: 'Purple Heart',
    base: '#7848B8', mid: '#5E38A0', shadow: '#401C78', edge: '#280E50',
    grainGap: 5, grainOp: 0.29,
    desc: 'Exotic South American hardwood. Dense and resonant.'
  }
};

const SURFACES = {
  crystal: {
    id: 'crystal', label: 'Crystal',
    base: '#B4D8F0', hi: '#DDEEFF', mid: '#82AECF',
    desc: 'Works wet or dry. Crisp, high-carrying yelps.'
  },
  aluminum: {
    id: 'aluminum', label: 'Anodized Aluminum',
    base: '#8A98A8', hi: '#BECAD4', mid: '#5E6E7C',
    desc: 'All-weather durability. Consistent metallic tone.'
  },
  slate: {
    id: 'slate', label: 'Slate',
    base: '#484858', hi: '#686878', mid: '#303040',
    desc: 'Classic natural surface. Rich, raspy yelps.'
  },
  ceramic: {
    id: 'ceramic', label: 'Ceramic',
    base: '#F0EDE0', hi: '#FDFCF8', mid: '#CCCABF',
    desc: 'Smooth and versatile. Soft purrs to aggressive cuts.'
  },
  glass: {
    id: 'glass', label: 'Glass',
    base: '#D4EEF8', hi: '#EEF8FF', mid: '#9DC8E2',
    desc: 'Clear, carrying tone. Excellent in wet weather.'
  }
};

/* ─────────────────────────── HELPERS ──────────────────────── */

function seededRng(seed) {
  let s = Math.abs(seed) % 233280;
  return () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
}

function strikerPoly(x1, y1, x2, y2, hw, tw) {
  const dx = x2 - x1, dy = y2 - y1;
  const d  = Math.sqrt(dx * dx + dy * dy);
  const nx = -dy / d, ny = dx / d;
  return [
    [x1 + nx * hw, y1 + ny * hw],
    [x2 + nx * tw, y2 + ny * tw],
    [x2 - nx * tw, y2 - ny * tw],
    [x1 - nx * hw, y1 - ny * hw]
  ].map(([x, y]) => `${x.toFixed(2)},${y.toFixed(2)}`).join(' ');
}

/* ─────────────────────────── SVG ───────────────────────────── */

function PotCallSVG({ woodType, surface }) {
  const wood = WOODS[woodType];
  const surf = SURFACES[surface];

  const cx = 250, ty = 208, by = 286, rx = 128, ry = 38;
  const lx = cx - rx, rx2 = cx + rx;
  const bulge = 10, bh = Math.round((by - ty) * 0.28);

  const bodyPath = [
    `M ${lx} ${ty}`,
    `A ${rx} ${ry} 0 0 1 ${rx2} ${ty}`,
    `C ${rx2+bulge} ${ty+bh}, ${rx2+bulge} ${by-bh}, ${rx2} ${by}`,
    `A ${rx} ${ry} 0 0 1 ${lx} ${by}`,
    `C ${lx-bulge} ${by-bh}, ${lx-bulge} ${ty+bh}, ${lx} ${ty}`
  ].join(' ');

  const srx = rx - 32, sry = ry - 10;

  const grainLines = useMemo(() => {
    const seed = woodType.split('').reduce((a, c, i) => a + c.charCodeAt(0) * (i + 1), 0);
    const rng  = seededRng(seed);
    const lines = [];
    for (let y = ty + wood.grainGap; y < by - 1; y += wood.grainGap) {
      lines.push({
        y:    y + (rng() - 0.5) * 1.4,
        op:   wood.grainOp * (0.22 + rng() * 0.88),
        wave: (rng() - 0.5) * 5
      });
    }
    return lines;
  }, [woodType]);

  const scratchLines = useMemo(() => {
    const seed = surface.split('').reduce((a, c, i) => a + c.charCodeAt(0) * (i + 1), 0);
    const rng  = seededRng(seed);
    return Array.from({ length: 7 }, () => {
      const lcx   = cx + (rng() - 0.5) * (rx - 32) * 1.2;
      const lcy   = ty + (rng() - 0.5) * (ry - 10) * 1.0;
      const angle = rng() * Math.PI;
      const len   = (rx - 32) * (0.2 + rng() * 0.5);
      return {
        x1: lcx - Math.cos(angle) * len, y1: lcy - Math.sin(angle) * len * 0.28,
        x2: lcx + Math.cos(angle) * len, y2: lcy + Math.sin(angle) * len * 0.28,
        op: 0.07 + rng() * 0.13
      };
    });
  }, [surface]);

  const s1x = rx2 + 72, s1y = by + 20;
  const s2x = rx2 - 6,  s2y = ty + 16;
  const stPts     = strikerPoly(s1x, s1y, s2x, s2y, 5, 1.8);
  const stShadPts = strikerPoly(s1x + 2, s1y + 3, s2x + 2, s2y + 3, 5, 1.8);
  const stHlPts   = strikerPoly(s1x, s1y, s2x, s2y, 2, 0.8);

  return (
    <svg viewBox="30 128 470 265" xmlns="http://www.w3.org/2000/svg"
         style={{ width: '100%', height: '100%', display: 'block', overflow: 'visible' }}>
      <defs>
        <filter id="fBlur">  <feGaussianBlur stdDeviation="7"/>   </filter>
        <filter id="fBlur2"> <feGaussianBlur stdDeviation="2.5"/> </filter>

        <clipPath id="cpBody"><path d={bodyPath}/></clipPath>
        <clipPath id="cpSurf"><ellipse cx={cx} cy={ty} rx={srx} ry={sry}/></clipPath>

        <linearGradient id="gCylShade" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%"   stopColor="black" stopOpacity="0.44"/>
          <stop offset="9%"   stopColor="white" stopOpacity="0.13"/>
          <stop offset="38%"  stopColor="white" stopOpacity="0.04"/>
          <stop offset="72%"  stopColor="black" stopOpacity="0.02"/>
          <stop offset="100%" stopColor="black" stopOpacity="0.54"/>
        </linearGradient>

        <linearGradient id="gWoodDark" x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%"   stopColor={wood.mid}   stopOpacity="0"/>
          <stop offset="100%" stopColor={wood.shadow} stopOpacity="0.62"/>
        </linearGradient>

        <radialGradient id="gRim" cx="38%" cy="30%" r="72%">
          <stop offset="0%"   stopColor={wood.base}/>
          <stop offset="60%"  stopColor={wood.mid}/>
          <stop offset="100%" stopColor={wood.shadow}/>
        </radialGradient>

        <radialGradient id="gSurf" cx="36%" cy="30%" r="70%">
          <stop offset="0%"   stopColor={surf.hi}/>
          <stop offset="50%"  stopColor={surf.base}/>
          <stop offset="100%" stopColor={surf.mid}/>
        </radialGradient>

        <linearGradient id="gStriker" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%"   stopColor={wood.mid}/>
          <stop offset="30%"  stopColor={wood.base}/>
          <stop offset="100%" stopColor={wood.shadow}/>
        </linearGradient>

        <radialGradient id="gBgGlow" cx="50%" cy="50%" r="42%">
          <stop offset="0%"   stopColor={wood.base} stopOpacity="0.07"/>
          <stop offset="100%" stopColor={wood.base} stopOpacity="0"/>
        </radialGradient>
      </defs>

      <rect x="30" y="128" width="470" height="265" fill="url(#gBgGlow)"/>

      <ellipse cx={cx} cy={by + 46} rx={rx * 0.86} ry={12}
               fill="black" opacity="0.28" filter="url(#fBlur)"/>

      {/* Barrel body */}
      <path d={bodyPath} fill={wood.base}/>
      <g clipPath="url(#cpBody)">
        {grainLines.map(({ y, op, wave }, i) => (
          <path key={i}
                d={`M ${lx-5} ${y} Q ${cx} ${y + wave} ${rx2+5} ${y}`}
                fill="none" stroke={wood.shadow} strokeWidth="0.95" opacity={op}/>
        ))}
        <ellipse cx={cx - rx*0.30} cy={ty + (by-ty)*0.60}
                 rx={rx*0.13} ry={(by-ty)*0.11}
                 fill={wood.shadow} opacity="0.20"/>
        <ellipse cx={cx + rx*0.20} cy={ty + (by-ty)*0.38}
                 rx={rx*0.08} ry={(by-ty)*0.07}
                 fill={wood.shadow} opacity="0.12"/>
      </g>
      <path d={bodyPath} fill="url(#gWoodDark)"/>
      <path d={bodyPath} fill="url(#gCylShade)"/>
      <path d={`M ${lx} ${by} A ${rx} ${ry} 0 0 0 ${rx2} ${by}`}
            fill="none" stroke={wood.edge} strokeWidth="2" opacity="0.85"/>

      {/* Top face */}
      <ellipse cx={cx} cy={ty} rx={rx} ry={ry} fill="url(#gRim)"/>
      <ellipse cx={cx} cy={ty} rx={rx} ry={ry} fill="url(#gCylShade)"/>
      <ellipse cx={cx} cy={ty} rx={srx + 5} ry={sry + 2}
               fill="none" stroke="black" strokeWidth="5" opacity="0.22"/>

      {/* Surface material */}
      <ellipse cx={cx} cy={ty} rx={srx} ry={sry} fill="url(#gSurf)"/>
      <g clipPath="url(#cpSurf)">
        {scratchLines.map(({ x1, y1, x2, y2, op }, i) => (
          <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
                stroke="white" strokeWidth="0.6" opacity={op}/>
        ))}
      </g>

      {surface === 'slate' && (
        <g clipPath="url(#cpSurf)">
          {[...Array(12)].map((_, i) => {
            const ySl = ty - sry + i * (sry * 2 / 11);
            return <line key={i} x1={lx} y1={ySl} x2={rx2} y2={ySl}
                         stroke={surf.mid} strokeWidth="0.7" opacity="0.4"/>;
          })}
        </g>
      )}

      {surface === 'aluminum' && (
        <g clipPath="url(#cpSurf)">
          {[...Array(18)].map((_, i) => {
            const ySl = ty - sry + i * (sry * 2 / 17);
            return <line key={i} x1={lx} y1={ySl} x2={rx2} y2={ySl}
                         stroke="white" strokeWidth="0.4" opacity="0.12"/>;
          })}
        </g>
      )}

      {(surface === 'crystal' || surface === 'glass') && (
        <ellipse cx={cx - srx*0.28} cy={ty - sry*0.36}
                 rx={srx*0.28} ry={sry*0.26}
                 fill="white" opacity="0.22" clipPath="url(#cpSurf)"/>
      )}

      {surface === 'ceramic' && (
        <ellipse cx={cx - srx*0.3} cy={ty - sry*0.4}
                 rx={srx*0.2} ry={sry*0.18}
                 fill="white" opacity="0.18" clipPath="url(#cpSurf)"/>
      )}

      <ellipse cx={cx} cy={ty} rx={srx} ry={sry}
               fill="none" stroke="black" strokeWidth="2" opacity="0.18"/>
      <ellipse cx={cx} cy={ty} rx={rx - 1} ry={ry - 0.5}
               fill="none" stroke={wood.base} strokeWidth="1.2" opacity="0.35"/>

      {/* Striker */}
      <polygon points={stShadPts} fill="black" opacity="0.22" filter="url(#fBlur2)"/>
      <polygon points={stPts}     fill="url(#gStriker)"/>
      <polygon points={stHlPts}   fill="white" opacity="0.22"/>
      <polygon points={stPts}     fill="none" stroke={wood.edge} strokeWidth="0.5" opacity="0.4"/>
      <circle  cx={s2x} cy={s2y} r="2.2" fill={wood.edge} opacity="0.72"/>
    </svg>
  );
}

/* ─────────────────────────── COMPONENT ───────────────────── */

function PotCallBuilder() {
  const [woodType,     setWoodType]     = useState('maple');
  const [surface,      setSurface]      = useState('crystal');
  const [previewFlash, setPreviewFlash] = useState(false);

  useEffect(() => {
    setPreviewFlash(true);
    const t = setTimeout(() => setPreviewFlash(false), 200);
    return () => clearTimeout(t);
  }, [woodType, surface]);

  const wood = WOODS[woodType];
  const surf = SURFACES[surface];

  return (
    <div className="max-w-[1100px] mx-auto bg-white rounded-lg shadow-md overflow-hidden">
      <div className="flex flex-col md:flex-row">

        {/* Left: SVG Preview */}
        <div
          className="md:w-[55%] p-6 flex items-center justify-center bg-gray-50 transition duration-150"
          style={{ boxShadow: previewFlash ? 'inset 0 0 0 2px #C8A45A' : 'none' }}
        >
          <div className="w-full max-w-[520px]">
            <PotCallSVG woodType={woodType} surface={surface} />
          </div>
        </div>

        {/* Right: Options */}
        <div className="md:w-[45%] p-8 border-l border-gray-200 flex flex-col">
          <div className="mb-6">
            <h1
              className="text-2xl font-semibold text-gray-900 leading-tight"
              style={{ fontFamily: "'Oswald', sans-serif" }}
            >
              Pot Call
            </h1>
            <p className="text-sm text-gray-500 mt-1">Green Swamp Turkey Calls</p>
          </div>

          <h2 className="text-xs font-semibold text-gray-700 mb-5 uppercase tracking-wide">
            Configure Your Call
          </h2>

          <div className="space-y-5 flex-1">

            {/* Wood Body */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">
                Wood Body
              </label>
              <select
                value={woodType}
                onChange={e => setWoodType(e.target.value)}
                className={SELECT}
              >
                {Object.values(WOODS).map(w => (
                  <option key={w.id} value={w.id}>{w.label}</option>
                ))}
              </select>
              <p className="text-xs text-gray-400 mt-1.5 leading-relaxed">{wood.desc}</p>
            </div>

            {/* Striking Surface */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">
                Striking Surface
              </label>
              <select
                value={surface}
                onChange={e => setSurface(e.target.value)}
                className={SELECT}
              >
                {Object.values(SURFACES).map(s => (
                  <option key={s.id} value={s.id}>{s.label}</option>
                ))}
              </select>
              <p className="text-xs text-gray-400 mt-1.5 leading-relaxed">{surf.desc}</p>
            </div>

            {/* Custom Wood Burning */}
            <div className="border-t border-gray-200 pt-5 !mt-7">
              <h3 className="text-sm font-semibold text-gray-800 mb-1">
                Custom Wood Burning
              </h3>
              <p className="text-xs text-gray-500 leading-relaxed mb-4">
                Custom wood burned artwork can be added for an additional charge.
                Contact us to discuss your design and receive a quote.
              </p>
              <a
                href="contact.html"
                className="flex items-center justify-center w-full py-2.5 px-4 rounded-lg text-sm font-medium text-white transition-colors"
                style={{ backgroundColor: BRAND }}
                onMouseEnter={e => e.currentTarget.style.backgroundColor = '#4A2C14'}
                onMouseLeave={e => e.currentTarget.style.backgroundColor = BRAND}
              >
                Contact Us About Wood Burning
              </a>
            </div>

          </div>
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('pot-call-builder')).render(<PotCallBuilder />);
