// MamaK&BabyPunn — affiliate link-in-bio app.
// Visitors can toggle the Tweaks panel (bottom-right ✨ button) to swap
// palette / font / sticker density. Choices persist in localStorage.

const { useState, useMemo } = React;

const PALETTES = {
  sage: {
    name: "Sage",
    bg1: "#EBEEE3", bg2: "#DFE5D3", card: "#F7F8F2",
    ink: "#2E332A", inkSoft: "#7E8576",
    accent: "#5A6B4E", accent2: "#C8B89A", accent3: "#B9C8A8", accent4: "#C2C9BA",
    chipBg: "#F7F8F2",
    ring: ["#5A6B4E", "#B9C8A8", "#C8B89A", "#C2C9BA", "#D6CFBE", "#5A6B4E"]
  },
  cream: {
    name: "Cream",
    bg1: "#FAF7F2", bg2: "#F3EEE6", card: "#FFFFFF",
    ink: "#2A2520", inkSoft: "#8C857C",
    accent: "#1A1A1A", accent2: "#E8C9A8", accent3: "#D5DCC6", accent4: "#CDD4DE",
    chipBg: "#FFFFFF",
    ring: ["#E8C9A8", "#EBD9C2", "#D5DCC6", "#CDD4DE", "#E6D2DE", "#E8C9A8"]
  },
  paper: {
    name: "Paper",
    bg1: "#FFFFFF", bg2: "#F6F6F4", card: "#FFFFFF",
    ink: "#111111", inkSoft: "#8A8A86",
    accent: "#111111", accent2: "#F2C8B4", accent3: "#CFE0D0", accent4: "#C9D4E3",
    chipBg: "#FFFFFF",
    ring: ["#F2C8B4", "#F0DCC2", "#E8E0C0", "#CFE0D0", "#C9D4E3", "#E6CCDB"]
  },
  sand: {
    name: "Sand",
    bg1: "#F2EDE3", bg2: "#E8E0D0", card: "#FBF8F2",
    ink: "#3A322A", inkSoft: "#9A8E7E",
    accent: "#3A322A", accent2: "#D6B89A", accent3: "#C8C6B0", accent4: "#BFC2BC",
    chipBg: "#FBF8F2",
    ring: ["#D6B89A", "#DDC9AC", "#C8C6B0", "#BFC2BC", "#D2BDC4", "#D6B89A"]
  },
  ink: {
    name: "Ink",
    bg1: "#F7F7F5", bg2: "#EEEEEC", card: "#FFFFFF",
    ink: "#0D0D0D", inkSoft: "#7A7A78",
    accent: "#0D0D0D", accent2: "#E0B89A", accent3: "#BFC9B8", accent4: "#B8C2CC",
    chipBg: "#FFFFFF",
    ring: ["#0D0D0D", "#E0B89A", "#BFC9B8", "#B8C2CC", "#C9B9C5", "#0D0D0D"]
  }
};

const FONT_PAIRS = {
  fredoka: { display: "'Fredoka', 'Mali', system-ui", body: "'Mali', 'Fredoka', system-ui", name: "Fredoka + Mali" },
  bubble:  { display: "'Baloo 2', 'Mali', system-ui", body: "'Mali', 'Baloo 2', system-ui", name: "Baloo + Mali" },
  cherry:  { display: "'Chewy', 'Mali', system-ui",   body: "'Mali', system-ui",            name: "Chewy + Mali" },
  serif:   { display: "'Fraunces', 'Mali', serif",    body: "'Mali', serif",                name: "Fraunces + Mali" }
};

// ─────────────────────────────────────────────────────────────
function Avatar({ palette }) {
  const ring = palette.ring;
  const conic = ring.map((c, i) => `${c} ${(i / ring.length) * 360}deg ${((i + 1) / ring.length) * 360}deg`).join(", ");
  return (
    <div style={{
      width: 132, height: 132, borderRadius: "50%",
      background: `conic-gradient(from -90deg, ${conic})`,
      padding: 5, position: "relative",
      animation: "spinSlow var(--ring-speed) linear infinite",
      boxShadow: "0 8px 24px rgba(0, 0, 0, .08)"
    }}>
      <div style={{
        width: "100%", height: "100%", borderRadius: "50%",
        background: "#fff", padding: 4, boxSizing: "border-box",
        animation: "spinSlowR var(--ring-speed) linear infinite"
      }}>
        <div style={{
          width: "100%", height: "100%", borderRadius: "50%",
          background: `linear-gradient(135deg, ${palette.accent2} 0%, ${palette.accent3} 55%, ${palette.accent4} 100%)`,
          display: "flex", alignItems: "center", justifyContent: "center",
          position: "relative", overflow: "hidden"
        }}>
          <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 62 }}>
            <span style={{ filter: "drop-shadow(0 2px 4px rgba(0,0,0,.12))" }}>🤱</span>
          </div>
        </div>
      </div>
      <div style={{ position: "absolute", top: -8, right: -4, width: 26, height: 26, animation: "wiggle 3s ease-in-out infinite" }}>
        <StarSticker color={palette.accent2}/>
      </div>
      <div style={{ position: "absolute", bottom: 2, left: -6, width: 20, height: 20, animation: "wiggle 4s ease-in-out .5s infinite" }}>
        <HeartSticker color={palette.accent3}/>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
function ShopeeIcon({ color = "#EE4D2D" }) {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true">
      <path d="M5 8h14l-1.2 12.5a1.5 1.5 0 0 1-1.5 1.5H7.7a1.5 1.5 0 0 1-1.5-1.5L5 8z" fill={color}/>
      <path d="M8.5 8V6.5a3.5 3.5 0 0 1 7 0V8" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round"/>
      <path d="M9.5 13.5c0 1.2 1.1 1.9 2.5 2.2 1.4.3 2.5 1 2.5 2.2 0 1.2-1.1 2-2.5 2-1.4 0-2.5-.5-3-1.3" fill="none" stroke="#fff" strokeWidth="1.3" strokeLinecap="round"/>
    </svg>
  );
}
function InstagramIcon({ color = "#E1306C" }) {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true">
      <rect x="3" y="3" width="18" height="18" rx="5" fill="none" stroke={color} strokeWidth="1.8"/>
      <circle cx="12" cy="12" r="3.8" fill="none" stroke={color} strokeWidth="1.8"/>
      <circle cx="17.5" cy="6.5" r="1.2" fill={color}/>
    </svg>
  );
}
function TikTokIcon({ color = "#111" }) {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true">
      <path d="M14 3 V14.5 C14 16.4 12.4 18 10.5 18 C8.6 18 7 16.4 7 14.5 C7 12.6 8.6 11 10.5 11 C10.8 11 11.1 11 11.3 11.1" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round"/>
      <path d="M14 3 C14 5.3 15.7 7 18 7" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round"/>
    </svg>
  );
}

function SocialRow() {
  const links = [
    { id: "shopee",    label: "Shopee",    color: "#EE4D2D", url: "#", Icon: ShopeeIcon },
    { id: "instagram", label: "Instagram", color: "#E1306C", url: "#", Icon: InstagramIcon },
    { id: "tiktok",    label: "TikTok",    color: "#111111", url: "#", Icon: TikTokIcon }
  ];
  return (
    <div className="social-row">
      {links.map(l => (
        <a key={l.id} href={l.url} className="social-pill" target="_blank" rel="noopener">
          <span className="social-icon"><l.Icon color={l.color}/></span>
          <span className="social-label">{l.label}</span>
        </a>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
function ProductCard({ p, palette, isFav, onFav }) {
  const platform = window.PLATFORMS[p.platform];
  const discount = p.original ? Math.round((1 - p.price / p.original) * 100) : 0;
  return (
    <a href={p.url || "#"} target="_blank" rel="noopener nofollow" className="prod-card">
      <div className="prod-img" style={{ background: `linear-gradient(135deg, ${p.swatch[0]} 0%, ${p.swatch[1]} 100%)` }}>
        <div className="prod-img-stripes"/>
        <div className="prod-emoji">{p.emoji}</div>
        {p.badge && <div className="prod-badge" style={{ background: palette.accent }}>{p.badge}</div>}
        {discount > 0 && <div className="prod-discount">-{discount}%</div>}
        <button className="prod-fav" onClick={(e) => { e.preventDefault(); e.stopPropagation(); onFav(p.id); }} aria-label="Favorite">
          <span style={{ filter: isFav ? "none" : "grayscale(1) opacity(.5)" }}>♥</span>
        </button>
      </div>
      <div className="prod-body">
        <div className="prod-name-th">{p.name_th}</div>
        <div className="prod-name-en">{p.name_en}</div>
        <div className="prod-row">
          <div className="prod-price-block">
            <span className="prod-price">฿{p.price}</span>
            {p.original && <span className="prod-original">฿{p.original}</span>}
          </div>
          <div className="prod-platform" style={{ background: platform.color, color: platform.text }}>{platform.name}</div>
        </div>
      </div>
    </a>
  );
}

// ─────────────────────────────────────────────────────────────
function ShopLink({ slotId, palette }) {
  const KEY = "shop-link-" + slotId;
  const [url, setUrl] = useState(() => localStorage.getItem(KEY) || "");
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(url);

  const save = () => {
    const v = draft.trim();
    setUrl(v);
    if (v) localStorage.setItem(KEY, v); else localStorage.removeItem(KEY);
    setEditing(false);
  };
  const clear = () => { setUrl(""); setDraft(""); localStorage.removeItem(KEY); setEditing(false); };

  const platform = useMemo(() => {
    if (!url) return null;
    const u = url.toLowerCase();
    if (u.includes("shopee"))    return { name: "Shopee",    color: "#EE4D2D" };
    if (u.includes("lazada"))    return { name: "Lazada",    color: "#3D2C8D" };
    if (u.includes("tiktok"))    return { name: "TikTok",    color: "#111111" };
    if (u.includes("instagram")) return { name: "Instagram", color: "#E1306C" };
    return { name: "Shop", color: palette.accent };
  }, [url, palette]);

  if (editing) {
    return (
      <div className="shop-edit">
        <input autoFocus type="url" className="shop-input" placeholder="paste Shopee / Lazada link…"
          value={draft} onChange={e => setDraft(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter") save(); if (e.key === "Escape") setEditing(false); }}/>
        <div className="shop-edit-row">
          <button className="shop-mini-btn shop-mini-primary" style={{ background: palette.accent, color: palette.bg1 }} onClick={save}>Save</button>
          {url && <button className="shop-mini-btn" onClick={clear}>Remove</button>}
          <button className="shop-mini-btn" onClick={() => setEditing(false)}>Cancel</button>
        </div>
      </div>
    );
  }
  if (!url) {
    return (
      <button className="shop-empty" onClick={() => { setDraft(""); setEditing(true); }}>
        <span className="shop-empty-plus">+</span>
        <span>เพิ่มลิงก์สินค้า · Add product link</span>
      </button>
    );
  }
  return (
    <div className="shop-filled">
      <a href={url} target="_blank" rel="noopener nofollow" className="shop-cta" style={{ background: platform.color, color: "#fff" }}>
        <span className="shop-cta-icon">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 8h14l-1 11.5a1.5 1.5 0 0 1-1.5 1.5H7.5a1.5 1.5 0 0 1-1.5-1.5z"/>
            <path d="M9 8V6a3 3 0 0 1 6 0v2"/>
          </svg>
        </span>
        <span className="shop-cta-label">ช้อปที่ {platform.name}</span>
        <span className="shop-cta-arrow">→</span>
      </a>
      <button className="shop-edit-btn" onClick={() => { setDraft(url); setEditing(true); }} title="Edit link">✎</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
function VideoReviewSlot({ slotId, palette, caption }) {
  const KEY = "vid-review-" + slotId;
  const [url, setUrl] = useState(() => localStorage.getItem(KEY) || "");
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(url);

  const save = () => {
    const v = draft.trim();
    setUrl(v);
    if (v) localStorage.setItem(KEY, v); else localStorage.removeItem(KEY);
    setEditing(false);
  };
  const clear = () => { setUrl(""); setDraft(""); localStorage.removeItem(KEY); };

  const embed = useMemo(() => {
    if (!url) return null;
    const u = url.trim();
    let m = u.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|shorts\/|embed\/))([\w-]{11})/);
    if (m) return { kind: "iframe", src: `https://www.youtube.com/embed/${m[1]}` };
    m = u.match(/tiktok\.com\/[@\w.-]+\/video\/(\d+)/);
    if (m) return { kind: "iframe", src: `https://www.tiktok.com/embed/v2/${m[1]}` };
    m = u.match(/instagram\.com\/(?:reel|p)\/([\w-]+)/);
    if (m) return { kind: "iframe", src: `https://www.instagram.com/p/${m[1]}/embed` };
    if (/\.(mp4|webm|mov)(\?|$)/i.test(u)) return { kind: "video", src: u };
    return { kind: "link", src: u };
  }, [url]);

  return (
    <div className="review-card review-video">
      {!url ? (
        editing ? (
          <div className="vid-edit">
            <input autoFocus type="url" className="vid-input" placeholder="paste TikTok / YT / IG link…"
              value={draft} onChange={e => setDraft(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") save(); if (e.key === "Escape") setEditing(false); }}/>
            <div className="vid-edit-row">
              <button className="vid-btn vid-btn-primary" style={{ background: palette.accent, color: palette.bg1 }} onClick={save}>Save</button>
              <button className="vid-btn" onClick={() => setEditing(false)}>Cancel</button>
            </div>
          </div>
        ) : (
          <button className="vid-empty" onClick={() => setEditing(true)}>
            <div className="vid-empty-icon">
              <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <rect x="2.5" y="5.5" width="14" height="13" rx="2.5"/>
                <path d="M16.5 10 L21 7.5 V16.5 L16.5 14"/>
              </svg>
            </div>
            <div className="vid-empty-label">Paste video link</div>
            <div className="vid-empty-sub">TikTok · YouTube · IG Reel</div>
          </button>
        )
      ) : (
        <>
          <div className="vid-frame">
            {embed.kind === "iframe" && (
              <iframe src={embed.src} allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen frameBorder="0" title="review"/>
            )}
            {embed.kind === "video" && (<video src={embed.src} controls playsInline/>)}
            {embed.kind === "link" && (
              <a href={embed.src} target="_blank" rel="noopener" className="vid-link">
                <div className="vid-link-icon">🔗</div>
                <div className="vid-link-text">Open review</div>
              </a>
            )}
          </div>
          <button className="vid-edit-mini" onClick={() => { setDraft(url); clear(); setTimeout(() => setEditing(true), 50); }} title="Replace">✎</button>
        </>
      )}
      <div className="review-caption">{caption}</div>
    </div>
  );
}

function ReviewsStrip({ palette }) {
  const slots = [
    { kind: "photo", id: "rev-1", caption: "Mama's pick 💌" },
    { kind: "video", id: "rev-2", caption: "Unboxing TikTok" },
    { kind: "photo", id: "rev-3", caption: "Punn loves it" },
    { kind: "photo", id: "rev-4", caption: "Real haul ✨" },
    { kind: "video", id: "rev-5", caption: "Honest review" }
  ];
  return (
    <section className="reviews-section">
      <div className="section-head">
        <div>
          <h2 className="section-title">
            Real reviews
            <span className="section-deco"><HeartSticker color={palette.accent2}/></span>
          </h2>
          <div className="section-sub">รีวิวจริงจากแม่กับลูก · drop photos or paste links</div>
        </div>
      </div>
      <div className="reviews-strip">
        {slots.map(s => (
          <div key={s.id} className="review-slot-wrap">
            {s.kind === "photo" ? (
              <div className="review-card review-photo">
                <image-slot id={s.id} shape="rounded" radius="16" fit="cover" placeholder="Drop photo"
                  style={{ width: "100%", height: "100%", display: "block" }}></image-slot>
                <div className="review-caption">{s.caption}</div>
              </div>
            ) : (
              <VideoReviewSlot slotId={s.id} palette={palette} caption={s.caption}/>
            )}
            <ShopLink slotId={s.id} palette={palette}/>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
const TWEAK_DEFAULTS = {
  vibe: "sage",
  font: "fredoka",
  decor: "light",
  ringSpeed: 22,
  showHelloBubble: true
};

const PALETTE_OPTIONS = [
  ["#B9C8A8", "#5A6B4E", "#C8B89A"], // sage
  ["#FAF7F2", "#E8C9A8", "#D5DCC6"], // cream
  ["#FFFFFF", "#F2C8B4", "#CFE0D0"], // paper
  ["#E8E0D0", "#D6B89A", "#C8C6B0"], // sand
  ["#F7F7F5", "#0D0D0D", "#E0B89A"]  // ink
];
const PALETTE_KEYS = ["sage", "cream", "paper", "sand", "ink"];

function App() {
  const [t, setTweak, resetTweaks] = useTweaks(TWEAK_DEFAULTS);
  const palette = PALETTES[t.vibe] || PALETTES.sage;
  const fonts = FONT_PAIRS[t.font] || FONT_PAIRS.fredoka;

  const [query, setQuery] = useState("");
  const [cat, setCat] = useState("all");
  const [favs, setFavs] = useState(() => new Set([3, 6]));

  const toggleFav = id => setFavs(prev => {
    const next = new Set(prev);
    if (next.has(id)) next.delete(id); else next.add(id);
    return next;
  });

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return window.PRODUCTS.filter(p => {
      if (cat !== "all" && p.category !== cat) return false;
      if (!q) return true;
      return (p.name_en + " " + p.name_th).toLowerCase().includes(q);
    });
  }, [query, cat]);

  const cssVars = {
    "--bg1": palette.bg1, "--bg2": palette.bg2, "--card": palette.card,
    "--ink": palette.ink, "--ink-soft": palette.inkSoft,
    "--accent": palette.accent, "--accent2": palette.accent2,
    "--accent3": palette.accent3, "--accent4": palette.accent4,
    "--chip-bg": palette.chipBg,
    "--font-display": fonts.display, "--font-body": fonts.body,
    "--ring-speed": `${t.ringSpeed}s`
  };

  // Selected palette swatch trio for the TweakColor picker.
  const currentSwatch = PALETTE_OPTIONS[PALETTE_KEYS.indexOf(t.vibe)] || PALETTE_OPTIONS[0];

  return (
    <div className="app-shell" style={cssVars}>
      <div className="bg-gradient" aria-hidden="true"/>
      <FloatingDecor density={t.decor}/>

      <main className="page">
        <div className="left-col">
          <div className="top-tag">
            <span className="dot" style={{ background: palette.accent3 }}/>
            <span>online & shopping 🛍️</span>
          </div>

          <section className="hero">
            <Avatar palette={palette}/>
            <h1 className="display-name">
              MamaK<span style={{ color: palette.accent }}>&</span>BabyPunn
            </h1>
            <div className="handle">@mamak.babypunn</div>
            <p className="bio">
              ของดีของแม่ ✨ แชร์ให้น้อง · A mama sharing finds<br/>
              👶 baby · 💄 beauty · 👗 fashion · 🍪 snacks
            </p>
            {t.showHelloBubble && (
              <div className="hello-bubble">
                <span>สวัสดีค่ะ! Click any link ↓</span>
                <div className="bubble-tail"/>
              </div>
            )}
          </section>

          <SocialRow/>
          <ReviewsStrip palette={palette}/>
        </div>

        <div className="right-col">
          <div className="search-wrap">
            <span className="search-icon">🔍</span>
            <input type="text" className="search-input" placeholder="ค้นหา · search the shoppe…"
              value={query} onChange={e => setQuery(e.target.value)}/>
            {query && (
              <button className="search-clear" onClick={() => setQuery("")} aria-label="Clear">✕</button>
            )}
          </div>

          <div className="chip-row">
            {window.CATEGORIES.map(c => (
              <button key={c.id} className={"chip " + (cat === c.id ? "chip-active" : "")}
                onClick={() => setCat(c.id)}
                style={cat === c.id ? { background: palette.accent, color: palette.bg1, borderColor: "transparent" } : {}}>
                <span className="chip-emoji">{c.emoji}</span>
                <span>{c.label_en}</span>
                <span className="chip-th">· {c.label_th}</span>
              </button>
            ))}
          </div>

          <div className="section-head">
            <div>
              <h2 className="section-title">
                {cat === "all" ? "Today's picks" : window.CATEGORIES.find(c => c.id === cat).label_en + " picks"}
                <span className="section-deco"><SparkleSticker color={palette.accent2}/></span>
              </h2>
              <div className="section-sub">
                {filtered.length} {filtered.length === 1 ? "item" : "items"} · อัพเดททุกสัปดาห์
              </div>
            </div>
          </div>

          {filtered.length === 0 ? (
            <div className="empty">
              <div className="empty-emoji">🥺</div>
              <div className="empty-title">ไม่พบสินค้า</div>
              <div className="empty-sub">No products match — try another search</div>
            </div>
          ) : (
            <div className="prod-grid">
              {filtered.map(p => (
                <ProductCard key={p.id} p={p} palette={palette} isFav={favs.has(p.id)} onFav={toggleFav}/>
              ))}
            </div>
          )}

          <footer className="foot">
            <div className="foot-rainbow"><RainbowSticker/></div>
            <div className="foot-msg">
              made with 💕 by Mama K<br/>
              <span className="foot-sub">ขอบคุณที่แวะมานะคะ · thanks for stopping by</span>
            </div>
            <div className="foot-tiny">© 2026 · affiliate disclosure: I earn a small commission on purchases</div>
          </footer>
        </div>
      </main>

      <TweaksPanel title="Tweaks" onReset={resetTweaks}>
        <TweakSection label="Vibe"/>
        <TweakColor
          label="Palette"
          value={currentSwatch}
          options={PALETTE_OPTIONS}
          onChange={(v) => {
            const idx = PALETTE_OPTIONS.findIndex(opt => opt[0] === v[0]);
            setTweak("vibe", PALETTE_KEYS[idx] || "sage");
          }}
        />
        <TweakSelect
          label="Font pair"
          value={t.font}
          options={Object.keys(FONT_PAIRS).map(k => ({ value: k, label: FONT_PAIRS[k].name }))}
          onChange={(v) => setTweak("font", v)}
        />
        <TweakSection label="Decoration"/>
        <TweakRadio
          label="Stickers"
          value={t.decor}
          options={["none", "light", "medium", "lots"]}
          onChange={(v) => setTweak("decor", v)}
        />
        <TweakSlider
          label="Ring spin"
          value={t.ringSpeed}
          min={4} max={40} step={1} unit="s"
          onChange={(v) => setTweak("ringSpeed", v)}
        />
        <TweakToggle
          label="Hello bubble"
          value={t.showHelloBubble}
          onChange={(v) => setTweak("showHelloBubble", v)}
        />
      </TweaksPanel>
    </div>
  );
}

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