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

// ----- palette (18 colors = the actual filament inventory; same list reused
//        for all 3 macaron layers so user can pick any colour for any layer) -----
const PALETTE = [
  { name: "Ivory White",     hex: "#FFFFFF", text: "#444"    },
  { name: "Sakura Pink",     hex: "#E8AFCF", text: "#5a2030" },
  { name: "Caramel",         hex: "#AE835B", text: "#fff"    },
  { name: "Lilac Purple",    hex: "#AE96D4", text: "#fff"    },
  { name: "Mandarin Orange", hex: "#F99963", text: "#5a2010" },
  { name: "Lemon Yellow",    hex: "#F7D959", text: "#5a4500" },
  { name: "Plum",            hex: "#950051", text: "#fff"    },
  { name: "Scarlet Red",     hex: "#DE4343", text: "#fff"    },
  { name: "Dark Green",      hex: "#68724D", text: "#fff"    },
  { name: "Grass Green",     hex: "#61C680", text: "#fff"    },
  { name: "Dark Blue",       hex: "#042F56", text: "#fff"    },
  { name: "Sky Blue",        hex: "#56B7E6", text: "#1f3a55" },
  { name: "Marine Blue",     hex: "#0078BF", text: "#fff"    },
  { name: "Nardo Gray",      hex: "#757575", text: "#fff"    },
  { name: "Charcoal",        hex: "#000000", text: "#fff"    },
  { name: "Desert Tan",      hex: "#E8DBB7", text: "#5a4520" },
  { name: "Latte Brown",     hex: "#D3B7A7", text: "#5a4520" },
  { name: "Dark Chocolate",  hex: "#4D3324", text: "#fff"    },
];
const BASE_COLORS   = PALETTE;
const KEY_COLORS    = PALETTE;
const LETTER_COLORS = PALETTE;

const PRICE_RON = 28.70;
const pickHex = (arr) => arr[Math.floor(Math.random() * arr.length)].hex;

// ---------- click sound — copied verbatim from clickaboo_keys/configurator.jsx ----------
let audioCtx = null;
function clickSound() {
  try {
    if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    const ctx = audioCtx;
    const sr = ctx.sampleRate;
    const now = ctx.currentTime;

    // 1) High, very short click transient (the "tick")
    const burstLen = Math.floor(sr * 0.012);
    const buf = ctx.createBuffer(1, burstLen, sr);
    const data = buf.getChannelData(0);
    for (let i = 0; i < burstLen; i++) {
      const env = Math.pow(1 - i / burstLen, 2.2);
      data[i] = (Math.random() * 2 - 1) * env;
    }
    const src = ctx.createBufferSource();
    src.buffer = buf;
    const bp = ctx.createBiquadFilter();
    bp.type = "bandpass";
    bp.frequency.value = 5500 + Math.random() * 800;
    bp.Q.value = 4.5;
    const hp = ctx.createBiquadFilter();
    hp.type = "highpass";
    hp.frequency.value = 2500;
    const ng = ctx.createGain();
    ng.gain.value = 0.85;
    src.connect(bp).connect(hp).connect(ng).connect(ctx.destination);
    src.start(now);

    // 2) Pitched "tink" pulse
    const o = ctx.createOscillator();
    const og = ctx.createGain();
    o.type = "sine";
    o.frequency.setValueAtTime(3800 + Math.random() * 400, now);
    o.frequency.exponentialRampToValueAtTime(2200, now + 0.012);
    og.gain.setValueAtTime(0.0001, now);
    og.gain.exponentialRampToValueAtTime(0.18, now + 0.001);
    og.gain.exponentialRampToValueAtTime(0.0001, now + 0.018);
    o.connect(og).connect(ctx.destination);
    o.start(now);
    o.stop(now + 0.022);

    // 3) Bottom-out tick 8ms later
    const t2 = now + 0.008;
    const buf2 = ctx.createBuffer(1, Math.floor(sr * 0.008), sr);
    const d2 = buf2.getChannelData(0);
    for (let i = 0; i < d2.length; i++) {
      d2[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / d2.length, 2);
    }
    const src2 = ctx.createBufferSource();
    src2.buffer = buf2;
    const bp2 = ctx.createBiquadFilter();
    bp2.type = "bandpass";
    bp2.frequency.value = 7500;
    bp2.Q.value = 6;
    const ng2 = ctx.createGain();
    ng2.gain.value = 0.6;
    src2.connect(bp2).connect(ng2).connect(ctx.destination);
    src2.start(t2);
  } catch (e) {}
}

// ---------- swatch row (copied from keys) ----------
function SwatchRow({ label, options, value, onChange }) {
  return (
    <div className="cf-section">
      <div className="cf-row-head">
        <span className="cf-label">{label}</span>
        <span className="cf-value">{options.find((o) => o.hex === value)?.name}</span>
      </div>
      <div className="cf-swatches">
        {options.map((o) => (
          <button
            key={o.hex}
            className={`cf-swatch ${value === o.hex ? "is-on" : ""}`}
            style={{ background: o.hex }}
            onClick={() => onChange(o.hex)}
            title={o.name}
            aria-label={o.name}
          >
            {value === o.hex && (
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 7.5L6 10.5L11 4.5" stroke={o.text} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            )}
          </button>
        ))}
      </div>
    </div>
  );
}

function Chip({ color, label }) {
  return (
    <div className="cf-chip">
      <span className="cf-chip-dot" style={{ background: color }}/>
      <span>{label}</span>
    </div>
  );
}

// ---------- 3D preview ----------
function Macaron3D({ accent, topColor, middleColor, baseColor, soundOn }) {
  const topProp    = useMemo(() => ({ url: "models/macaroon_top.stl",    color: topColor    }), [topColor]);
  const middleProp = useMemo(() => ({ url: "models/macaroon_middle.stl", color: middleColor }), [middleColor]);
  const baseProp   = useMemo(() => ({ url: "models/macaroon_base.stl",   color: baseColor   }), [baseColor]);
  const [pressedOnce, setPressedOnce] = React.useState(false);
  const handlePress = React.useCallback(() => {
    if (soundOn) clickSound();
    setPressedOnce(true);
  }, [soundOn]);
  return (
    <div className="kb-stage">
      <div className="kb-platter" style={{ background: `radial-gradient(ellipse at center, ${accent}22, transparent 60%)` }}/>
      <window.MacaronViewer top={topProp} middle={middleProp} base={baseProp} onPress={handlePress} />
      <div className={`cf-hint-bubble ${pressedOnce ? "is-hidden" : ""}`} aria-hidden="true">
        Apasă macaronul <span className="cf-hint-icon">🔊</span>
      </div>
      <div className="kb-hint">drag pentru rotire · scroll pentru zoom · click pe macaron</div>
    </div>
  );
}

// ---------- main app ----------
const STATE_KEY = "clickaroons:state";
function loadSaved() {
  try { return JSON.parse(sessionStorage.getItem(STATE_KEY)) || {}; } catch (e) { return {}; }
}

function App() {
  const tweaksDefaults = /*EDITMODE-BEGIN*/{
    "accent": "#3D6BFF"
  }/*EDITMODE-END*/;
  const [tweaks, setTweak] = window.useTweaks(tweaksDefaults);

  // Restore last selections from this tab if user came back; otherwise random on arrival.
  const saved = loadSaved();
  const [topColor,    setTopColor]    = useState(() => saved.topColor    || pickHex(LETTER_COLORS));
  const [middleColor, setMiddleColor] = useState(() => saved.middleColor || pickHex(KEY_COLORS));
  const [baseColor,   setBaseColor]   = useState(() => saved.baseColor   || pickHex(BASE_COLORS));
  const [soundOn,     setSoundOn]     = useState(() => typeof saved.soundOn === "boolean" ? saved.soundOn : true);

  useEffect(() => {
    try { sessionStorage.setItem(STATE_KEY, JSON.stringify({ topColor, middleColor, baseColor, soundOn })); } catch (e) {}
  }, [topColor, middleColor, baseColor, soundOn]);

  const surprise = () => {
    setTopColor(pickHex(LETTER_COLORS));
    setMiddleColor(pickHex(KEY_COLORS));
    setBaseColor(pickHex(BASE_COLORS));
    if (soundOn) clickSound();
  };

  const accent = tweaks.accent;

  return (
    <div className="cf-app" style={{ "--accent": accent }}>
      <aside className="cf-left">
        <header className="cf-header">
          <div className="cf-brand">
            <a href="/#hero" aria-label="Înapoi la Clickaboo" className="cf-brand-link">
              <img src="/assets/logo.svg" alt="Clickaboo" className="cf-brand-logo" />
            </a>
          </div>
          <div className="cf-step">Personalizează</div>
        </header>

        <div className="cf-scroll">
          <div className="cf-section">
            <div className="cf-extras">
              <button className="cf-extra-btn" onClick={surprise}>
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M2 4h3l2 4 2-4h3M2 12h3l2-4M11 12h3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/><circle cx="13.5" cy="3" r="1" fill="currentColor"/><circle cx="3" cy="14" r="1" fill="currentColor"/></svg>
                Surprinde-mă
              </button>
              <button
                className={`cf-extra-btn ${soundOn ? "is-on" : ""}`}
                onClick={() => { setSoundOn(!soundOn); if (!soundOn) clickSound(); }}
              >
                {soundOn ? (
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 6v4h2l3 3V3L5 6H3zM10.5 5.5a3 3 0 010 5M12.5 3.5a6 6 0 010 9" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                ) : (
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 6v4h2l3 3V3L5 6H3zM11 6l4 4M15 6l-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                )}
                Sunet click {soundOn ? "pornit" : "oprit"}
              </button>
            </div>
          </div>

          <SwatchRow label="Blat 1" options={LETTER_COLORS} value={topColor}    onChange={setTopColor} />
          <SwatchRow label="Crema"  options={KEY_COLORS}    value={middleColor} onChange={setMiddleColor} />
          <SwatchRow label="Blat 2" options={BASE_COLORS}   value={baseColor}   onChange={setBaseColor} />
        </div>

        <footer className="cf-footer">
          <div className="cf-price-row">
            <div>
              <div className="cf-price-label">Total</div>
              <div className="cf-price-sub">include printare & breloc</div>
            </div>
            <div className="cf-price">{PRICE_RON} RON</div>
          </div>
          <button className="cf-checkout" style={{ background: accent }} onClick={() => {
            if (soundOn) clickSound();
            const params = new URLSearchParams({ from: "clickaroons", price: PRICE_RON.toFixed(2) });
            window.location.href = `/keychains/?${params}`;
          }}>
            Urmatorul Pas
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </footer>
      </aside>

      <main className="cf-right">
        <div className="cf-stage-meta">
          <div className="cf-stage-title">
            <span className="cf-stage-label">Previzualizare</span>
            <span className="cf-stage-sku">CR-MAC</span>
          </div>
        </div>
        <Macaron3D accent={accent} topColor={topColor} middleColor={middleColor} baseColor={baseColor} soundOn={soundOn} />
        <div className="cf-legend">
          <Chip color={topColor}    label="Blat 1" />
          <Chip color={middleColor} label="Crema" />
          <Chip color={baseColor}   label="Blat 2" />
        </div>
      </main>

      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="UI Accent">
          <window.TweakColor
            label="Accent"
            value={tweaks.accent}
            onChange={(v) => setTweak("accent", v)}
            options={["#3D6BFF", "#E85A4F", "#1A1A1E", "#40B080"]}
          />
        </window.TweakSection>
      </window.TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
