const { CountryFlag, Icon } = window.EdvinDesignSystem_ae67eb;
const LIGHT = { fontWeight: 300, letterSpacing: "0.01em" };
const fold = (s) => String(s == null ? "" : s).normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[’']/g, "").toLowerCase();
const ROW_H = 68;

function Stepper({ value, onChange, min = 1 }) {
  const btn = (sign, next, disabled) => (
    <button type="button" disabled={disabled} onClick={() => onChange(next)} aria-label={sign === "+" ? "Mehr" : "Weniger"} style={{
      width: 44, height: 44, borderRadius: 10, border: "none", cursor: disabled ? "default" : "pointer",
      background: "transparent", color: disabled ? "var(--edvin-gray-400)" : "var(--edvin-black)",
      fontSize: 22, fontWeight: 300, lineHeight: 1, display: "grid", placeItems: "center",
    }}>{sign}</button>
  );
  return (
    <div style={{ display: "inline-flex", alignItems: "center", background: "var(--edvin-gray-100)", borderRadius: 12, padding: 2 }}>
      {btn("−", value - 1, value <= min)}
      <span style={{ minWidth: 34, textAlign: "center", fontSize: 17, fontWeight: 400 }}>{value}</span>
      {btn("+", value + 1, false)}
    </div>
  );
}

function Star({ filled, size = 15 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 20 20" aria-hidden="true" style={{ display: "block" }}>
      <path d="M10 1.6l2.6 5.3 5.8.85-4.2 4.1 1 5.75L10 14.9l-5.2 2.7 1-5.75L1.6 7.75l5.8-.85z"
        fill={filled ? "var(--edvin-green)" : "none"} stroke={filled ? "var(--edvin-green)" : "var(--edvin-gray-400)"} strokeWidth="1.3" strokeLinejoin="round" />
    </svg>
  );
}

function StarRating({ value = 0, onChange, size = 26 }) {
  return (
    <div role="group" aria-label="Bewertung" style={{ display: "flex", alignItems: "center", gap: 2, marginLeft: -6 }}>
      {[1, 2, 3, 4, 5].map((n) => (
        <button key={n} type="button" onClick={() => onChange(n)} aria-label={n + " von 5"} aria-pressed={value >= n} style={{
          width: 44, height: 44, display: "grid", placeItems: "center", background: "none", border: "none",
          padding: 0, cursor: "pointer", transition: "transform var(--duration-fast) var(--ease-standard)",
          transform: value === n ? "scale(1.08)" : "none",
        }}><Star filled={value >= n} size={size} /></button>
      ))}
      {value ? <span style={{ marginLeft: 4, fontSize: 13, color: "var(--edvin-gray-900)" }}>{value} von 5</span> : null}
    </div>
  );
}

function StarsStatic({ value, size = 11 }) {
  return (
    <span style={{ display: "inline-flex", gap: 1.5, alignItems: "center" }}>
      {[1, 2, 3, 4, 5].map((n) => <Star key={n} filled={value >= n} size={size} />)}
    </span>
  );
}

function PriceTag({ w, size = 15, align = "right" }) {
  return (
    <span style={{ display: "flex", flexDirection: "column", alignItems: align === "right" ? "flex-end" : "flex-start", lineHeight: 1.25, whiteSpace: "nowrap" }}>
      <span style={{ fontWeight: 700, fontSize: size, color: "var(--edvin-red)" }}>{window.TDOF.chf(w.sale)}</span>
      <span style={{ fontWeight: 400, fontSize: size - 3, color: "var(--edvin-gray-900)", textDecoration: "line-through" }}>{window.TDOF.chf(w.price)}</span>
    </span>
  );
}

function bottleSrc(w) {
  const R = window.__resources || {};
  if (w.img) return R["bottle-" + w.art] || w.img;
  return R.bottle || "./bottle-placeholder.png";
}

function Tag({ children }) {
  return <span style={{ display: "inline-block", padding: "4px 9px", borderRadius: 8, background: "var(--edvin-green-tint)", color: "var(--edvin-green)", fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".03em" }}>{children}</span>;
}

function WineDetail({ w, qty, setQty, note, setNote, rating, setRating, faved, onFave, onAdd, onCollapse }) {
  const [added, setAdded] = React.useState(false);
  return (
    <div style={{ padding: "4px 0 26px", display: "flex", flexDirection: "column", gap: 20 }}>
      <div style={{ display: "flex", gap: 18, alignItems: "flex-start" }}>
        <div style={{ flex: "0 0 88px", alignSelf: "flex-start" }}>
          <img src={bottleSrc(w)} alt="" style={{ width: 88, height: 168, objectFit: "contain", objectPosition: "center bottom", display: "block" }} />
        </div>
        <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 10 }}>
          <h3 style={{ margin: 0, fontSize: 21, lineHeight: 1.15, textTransform: "uppercase", ...LIGHT }}>{w.name}</h3>
          <div style={{ fontSize: 14, color: "var(--edvin-gray-900)", lineHeight: 1.5 }}>
            {w.producer}<br />
            {w.landLabel}{w.year ? " · " + w.year : ""} · {(w.size || "75cl").replace("cl", " cl")} · Art.-Nr. {w.art}
          </div>
          {w.tags.length > 0 && <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>{w.tags.map((t) => <Tag key={t}>{t}</Tag>)}</div>}
          <PriceTag w={w} size={22} align="left" />
        </div>
      </div>

      <div>
        <span style={{ display: "block", marginBottom: 2, fontSize: 16, color: "var(--edvin-gray-900)" }}>Meine Bewertung</span>
        <StarRating value={rating} onChange={setRating} />
      </div>

      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
        <Stepper value={qty} onChange={setQty} />
        <div style={{ display: "flex", flexDirection: "column", gap: 8, minWidth: 208, flex: "0 1 auto" }}>
          <button type="button" onClick={onFave} aria-pressed={faved} style={{
            height: 44, border: "none", borderRadius: 12, cursor: "pointer",
            background: faved ? "var(--edvin-green-tint)" : "var(--edvin-gray-100)",
            color: faved ? "var(--edvin-green)" : "var(--edvin-black)",
            fontFamily: "var(--font-core)", fontWeight: faved ? 700 : 400, fontSize: 14,
            textTransform: "uppercase", letterSpacing: ".06em",
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 9,
            transition: "background var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard)",
          }}>
            <Icon name="Favourite" size={15} />{faved ? "Gemerkt" : "Merken"}
          </button>
          <button type="button" onClick={() => { onAdd(qty); setAdded(true); setTimeout(() => setAdded(false), 1400); }} style={{
            height: 50, border: "none", borderRadius: 12, cursor: "pointer",
            background: added ? "var(--edvin-green)" : "var(--edvin-red)", color: "#fff",
            fontFamily: "var(--font-core)", fontWeight: 700, fontSize: 14,
            textTransform: "uppercase", letterSpacing: ".06em",
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 10,
            transition: "background var(--duration-fast) var(--ease-standard)",
          }}>
            <Icon name="Cart" size={17} />{added ? "Hinzugefügt" : "In den Warenkorb"}
          </button>
        </div>
      </div>

      <label style={{ display: "block" }}>
        <span style={{ display: "block", marginBottom: 8, fontSize: 16, color: "var(--edvin-gray-900)" }}>Meine Notizen</span>
        <textarea rows={3} value={note} onChange={(e) => setNote(e.target.value)} placeholder="Was ist dir aufgefallen?" style={{
          width: "100%", padding: "12px 14px", borderRadius: 12, border: "none",
          background: "var(--edvin-gray-100)", outline: "none", resize: "vertical",
          fontFamily: "var(--font-core)", fontSize: 16, lineHeight: 1.45, color: "var(--edvin-black)",
        }} />
      </label>

      <button type="button" onClick={onCollapse} style={{
        alignSelf: "center", height: 40, padding: "0 18px", background: "none", border: "none", cursor: "pointer",
        fontFamily: "var(--font-core)", fontSize: 14, color: "var(--edvin-gray-900)",
      }}>Zuklappen ⌃</button>
    </div>
  );
}

function WineRow({ w, open, onToggle, state, actions, last }) {
  const faved = !!state.faves[w.nr];
  const inCart = state.cart[w.nr] || 0;
  const rating = state.ratings[w.nr] || 0;
  return (
    <li>
      <button type="button" onClick={onToggle} aria-expanded={open} style={{
        width: "100%", height: ROW_H, display: "flex", alignItems: "center", gap: 14,
        padding: 0, background: "transparent", border: "none", cursor: "pointer", textAlign: "left",
      }}>
        <span style={{ flex: "0 0 30px", fontSize: 13, fontWeight: 400, color: "var(--edvin-gray-900)", fontVariantNumeric: "tabular-nums" }}>{w.nr}</span>
        <CountryFlag country={w.land} width={22} shape="circle" />
        <span style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 3 }}>
          <span style={{
            fontSize: 15, lineHeight: 1.2, textTransform: "uppercase", color: "var(--edvin-black)", fontWeight: 400, letterSpacing: "0.01em",
            display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden",
          }}>{w.name}</span>
          {(faved || inCart > 0 || rating > 0) && (
            <span style={{ display: "flex", gap: 10, alignItems: "center" }}>
              {faved && <span style={{ color: "var(--edvin-green)", display: "inline-flex" }}><Icon name="Favourite" size={12} /></span>}
              {rating > 0 && <StarsStatic value={rating} />}
              {inCart > 0 && <span style={{ color: "var(--edvin-red)", fontSize: 11, fontWeight: 700 }}>{inCart}× im Warenkorb</span>}
            </span>
          )}
        </span>
        <PriceTag w={w} />
        <span style={{ flex: "0 0 14px", color: "var(--edvin-gray-400)", fontSize: 17, lineHeight: 1, display: "grid", placeItems: "center", transform: open ? "rotate(180deg)" : "none", transition: "transform var(--duration-fast) var(--ease-standard)" }}>⌄</span>
      </button>
      {open && (
        <WineDetail w={w} qty={state.qty[w.nr] || 1} setQty={(n) => actions.setQty(w.nr, n)}
          note={state.notes[w.nr] || ""} setNote={(v) => actions.setNote(w.nr, v)}
          rating={state.ratings[w.nr] || 0} setRating={(n) => actions.setRating(w.nr, n)}
          faved={faved} onFave={() => actions.toggleFave(w.nr)}
          onAdd={(n) => actions.addToCart(w.nr, n)} onCollapse={onToggle} />
      )}
      {!last && <span style={{ display: "block", height: "0.5px", background: "rgba(0,0,0,0.14)", marginLeft: 62 }} />}
    </li>
  );
}

function CategoryJump({ categories, onJump }) {
  return (
    <div style={{ position: "relative" }}>
      <div className="tdof-scroll" style={{ display: "flex", gap: 22, overflowX: "auto", padding: "0 40px 14px 20px", scrollbarWidth: "none" }}>
        {categories.map((c) => (
          <button key={c.id} type="button" onClick={() => onJump(c.id)} style={{
            flex: "0 0 auto", minHeight: 44, display: "flex", alignItems: "center", padding: 0,
            background: "none", border: "none", cursor: "pointer", whiteSpace: "nowrap",
            fontFamily: "var(--font-core)", fontWeight: 300, fontSize: 15, letterSpacing: ".05em",
            textTransform: "uppercase", color: "var(--edvin-green)",
          }}>{c.title}</button>
        ))}
      </div>
      <span aria-hidden="true" style={{
        position: "absolute", top: 0, right: 0, bottom: 14, width: 84, pointerEvents: "none",
        background: "linear-gradient(to right, rgba(255,255,255,0) 0%, rgba(255,255,255,0.75) 42%, var(--edvin-white) 82%)",
      }} />
    </div>
  );
}

function SearchGlass({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="10.2 10.1 14.6 14.6" fill="none" stroke="currentColor"
      strokeWidth="1" strokeLinecap="round" aria-hidden="true" style={{ display: "block" }}>
      <circle cx="15.75" cy="15.2" r="4.55" />
      <path d="M19.05 18.65 L23.95 23.5" />
    </svg>
  );
}

function SearchBar({ q, setQ }) {
  return (
    <form role="search" autoComplete="off" onSubmit={(e) => e.preventDefault()} style={{ display: "flex", alignItems: "center", gap: 11, height: 48, padding: "0 8px 0 15px", borderRadius: 999, background: "var(--edvin-white)", boxShadow: "var(--inset-input)" }}>
      <span style={{ display: "grid", placeItems: "center", flex: "0 0 auto", color: "var(--edvin-black)" }}><SearchGlass /></span>
      <input type="search" name="weinsuche" autoComplete="off" autoCorrect="off" autoCapitalize="off" spellCheck={false} inputMode="search" enterKeyHint="search" data-form-type="other" data-lpignore="true" data-1p-ignore="true" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Wein, Nummer oder Herkunft suchen" style={{
        flex: 1, minWidth: 0, border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-core)", fontSize: 16, color: "var(--edvin-black)",
      }} />
      {q && (
        <button type="button" onClick={() => setQ("")} aria-label="Suche löschen" style={{
          width: 40, height: 40, flex: "0 0 auto", borderRadius: "50%", border: "none", background: "none", cursor: "pointer",
          display: "grid", placeItems: "center",
        }}>
          <span style={{ width: 22, height: 22, borderRadius: "50%", background: "var(--edvin-gray-400)", color: "#fff", fontSize: 13, lineHeight: "22px", textAlign: "center" }}>✕</span>
        </button>
      )}
    </form>
  );
}

function WineList({ state, actions, onlyFaves }) {
  const [open, setOpen] = React.useState(null);
  const [q, setQ] = React.useState("");
  const wrap = window.TDOF_WRAP;
  const term = fold(q.trim());
  const pass = (w) => !onlyFaves || state.faves[w.nr];

  const cats = window.TDOF.categories.map((c) => ({
    ...c,
    wines: c.wines.filter((w) =>
      pass(w) &&
      (!term || fold(w.name).includes(term) || fold(w.nr) === term || w.art.includes(term) ||
        fold(w.producer).includes(term) || fold(w.landLabel).includes(term))),
  })).filter((c) => c.wines.length > 0);

  const jump = (id) => {
    const el = document.getElementById("cat-" + id);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 104, behavior: "smooth" });
  };
  const total = cats.reduce((n, c) => n + c.wines.length, 0);

  return (
    <div>
      <div style={{ ...wrap, paddingTop: 22 }}>
        {onlyFaves ? (
          <h1 style={{ margin: "0 0 16px", fontSize: 34, lineHeight: 1.02, textTransform: "uppercase", color: "var(--edvin-green)", ...LIGHT }}>Meine Merkliste</h1>
        ) : (
          <h1 style={{ margin: "0 0 16px" }}>
            <img src={window.TDOF_BANNER} alt="Tag der offenen Flaschen 2026"
              style={{ display: "block", width: "100%", maxWidth: 342, height: "auto", margin: "0 auto" }} />
          </h1>
        )}
        <SearchBar q={q} setQ={setQ} />
      </div>

      {!onlyFaves && <div style={{ ...wrap, padding: 0, marginTop: 14 }}><CategoryJump categories={cats} onJump={jump} /></div>}

      {total === 0 && (
        <div style={{ ...wrap, padding: "48px 20px", textAlign: "center", color: "var(--edvin-gray-900)", fontSize: 15, lineHeight: 1.5 }}>
          {onlyFaves ? "Du hast noch keine Weine gemerkt." : "Keine Weine gefunden."}
        </div>
      )}

      {cats.map((c) => (
        <section key={c.id} id={"cat-" + c.id}>
          <div style={{ position: "sticky", top: 68, zIndex: 10, background: "var(--edvin-green)", color: "#fff" }}>
            <div style={{ ...wrap, height: 38, display: "flex", alignItems: "center" }}>
              <h2 style={{ margin: 0, fontSize: 14, textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 300 }}>{c.title}</h2>
            </div>
          </div>
          <ul style={{ ...wrap, listStyle: "none", padding: "0 20px" }}>
            {c.wines.map((w, i) => (
              <WineRow key={w.nr} w={w} open={open === w.nr} onToggle={() => setOpen(open === w.nr ? null : w.nr)}
                state={state} actions={actions} last={i === c.wines.length - 1} />
            ))}
          </ul>
        </section>
      ))}
    </div>
  );
}

Object.assign(window, { TdofWineList: WineList, TdofPriceTag: PriceTag, TdofStepper: Stepper, TdofStarsStatic: StarsStatic });
