// Home screen — 喝啥 YO
// Lightweight swipe-card discovery (Tinder-style).
// Buttons (✕ / ⭐ / ♡) write state and fade card down; horizontal swipe just
// pages to the next card without writing any state.

function HomeScreen({ onOpenBrand, onOpenDrink }) {
  const [brandFilter, setBrandFilter] = React.useState(null); // null = 全部
  const deck = React.useMemo(
    () => brandFilter ? DRINKS.filter(d => d.brandId === brandFilter) : DRINKS,
    [brandFilter],
  );
  const [index, setIndex] = React.useState(0);
  // exit: { dir: 'down' | 'left' | 'right', action: 'like' | 'maybe' | 'dislike' | null }
  const [exit, setExit] = React.useState(null);
  const [drag, setDrag] = React.useState({ x: 0, dragging: false });
  const [toast, setToast] = React.useState(null);
  const dragRef = React.useRef({ startX: 0, startY: 0, axis: null });
  const exitTimer = React.useRef(null);
  const toastTimer = React.useRef(null);

  React.useEffect(() => () => {
    if (exitTimer.current) clearTimeout(exitTimer.current);
    if (toastTimer.current) clearTimeout(toastTimer.current);
  }, []);

  const top = deck[index];
  const next1 = deck[index + 1];
  const next2 = deck[index + 2];

  const showToast = (text, color) => {
    if (toastTimer.current) clearTimeout(toastTimer.current);
    setToast({ text, color });
    toastTimer.current = setTimeout(() => setToast(null), 1200);
  };

  const triggerAction = (action) => {
    if (exit) return;
    const config = {
      like:    { text: '已收藏 · 在「收藏」里查看', color: 'var(--data-cal)' },
      maybe:   { text: '加入「再看看」', color: 'var(--brand-yellow-ink)' },
      dislike: { text: '已忽略', color: 'var(--ink-3)' },
    }[action];
    setExit({ dir: 'down', action });
    showToast(config.text, config.color);
    exitTimer.current = setTimeout(() => {
      setIndex((i) => i + 1);
      setExit(null);
      setDrag({ x: 0, dragging: false });
    }, 280);
  };

  const onPointerDown = (e) => {
    if (exit) return;
    e.currentTarget.setPointerCapture?.(e.pointerId);
    dragRef.current = { startX: e.clientX, startY: e.clientY, axis: null };
    setDrag({ x: 0, dragging: true });
  };
  const onPointerMove = (e) => {
    if (!drag.dragging || exit) return;
    const dx = e.clientX - dragRef.current.startX;
    const dy = e.clientY - dragRef.current.startY;
    if (!dragRef.current.axis) {
      if (Math.abs(dx) > 6 || Math.abs(dy) > 6) {
        dragRef.current.axis = Math.abs(dx) > Math.abs(dy) ? 'x' : 'y';
      }
    }
    if (dragRef.current.axis === 'x') {
      setDrag({ x: dx, dragging: true });
    }
  };
  const onPointerUp = (e) => {
    if (!drag.dragging) return;
    const dx = drag.x;
    const wasTap = dragRef.current.axis !== 'x' && Math.abs(dx) < 6;
    setDrag({ x: 0, dragging: false });

    if (wasTap) {
      // let the click through to inner buttons / card tap handler
      return;
    }
    if (Math.abs(dx) > 80 && dragRef.current.axis === 'x') {
      // horizontal swipe → next card (no state change)
      const dir = dx < 0 ? 'left' : 'right';
      setExit({ dir, action: null });
      exitTimer.current = setTimeout(() => {
        setIndex((i) => i + 1);
        setExit(null);
      }, 240);
    }
  };

  const onPointerCancel = () => {
    setDrag({ x: 0, dragging: false });
  };

  const restart = () => {
    setIndex(0);
    setExit(null);
    setDrag({ x: 0, dragging: false });
  };

  const pickBrand = (brandId) => {
    if (exitTimer.current) clearTimeout(exitTimer.current);
    if (toastTimer.current) clearTimeout(toastTimer.current);
    setBrandFilter(brandId);
    setIndex(0);
    setExit(null);
    setDrag({ x: 0, dragging: false });
    setToast(null);
  };

  return (
    <div style={{
      paddingBottom: 100, height: '100%',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Header — capsule placeholder + greeting + grid icon */}
      <HomeHeader />

      {/* Brand row — 点击品牌头像筛选下方饮品堆栈 */}
      <div style={{ padding: '4px 16px 6px',
                    display: 'flex', alignItems: 'baseline',
                    justifyContent: 'space-between' }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-1)' }}>
          近 2 周新品
        </span>
        <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>点 logo 只看这家</span>
      </div>
      <div className="scroll" style={{
        display: 'flex', gap: 16, overflowX: 'auto',
        padding: '4px 16px 12px',
      }}>
        {/* 全部 chip */}
        <button onClick={() => pickBrand(null)} style={{
          flexShrink: 0, display: 'flex', flexDirection: 'column',
          alignItems: 'center', gap: 6, background: 'transparent',
          border: 0, padding: 0, cursor: 'pointer',
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: '50%',
            background: brandFilter == null ? 'var(--ink-1)' : 'var(--surface)',
            color: brandFilter == null ? '#fff' : 'var(--ink-2)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 13, fontWeight: 600,
            boxShadow: brandFilter == null
              ? '0 0 0 3px rgba(28,23,16,0.10), var(--sh-1)'
              : 'inset 0 0 0 0.5px rgba(0,0,0,0.06), var(--sh-1)',
            transition: 'all 200ms ease',
          }}>
            全部
          </div>
          <span style={{
            fontSize: 10, fontWeight: brandFilter == null ? 600 : 500,
            color: brandFilter == null ? 'var(--ink-1)' : 'var(--ink-3)',
          }}>
            全部
          </span>
        </button>

        {BRANDS.slice(0, 6).map(b => {
          const active = brandFilter === b.id;
          return (
            <button key={b.id} onClick={() => pickBrand(b.id)} style={{
              flexShrink: 0, display: 'flex', flexDirection: 'column',
              alignItems: 'center', gap: 6, background: 'transparent',
              border: 0, padding: 0, cursor: 'pointer',
            }}>
              <div style={{
                width: 56, height: 56, borderRadius: '50%',
                background: b.color, color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 22, fontWeight: 700, letterSpacing: 0.5,
                boxShadow: active
                  ? `0 0 0 3px ${b.color}66, var(--sh-2)`
                  : 'var(--sh-1)',
                opacity: brandFilter && !active ? 0.5 : 1,
                transition: 'all 200ms ease',
              }}>
                {b.glyph}
              </div>
              <span style={{
                fontSize: 10,
                fontWeight: active ? 600 : 500,
                color: active ? 'var(--ink-1)' : 'var(--ink-3)',
              }}>
                {b.name}
              </span>
            </button>
          );
        })}
      </div>

      {/* Card deck */}
      <div style={{
        flex: 1, position: 'relative',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        margin: '8px 16px 0',
      }}>
        {/* toast */}
        {toast && (
          <div style={{
            position: 'absolute', top: 0, left: '50%',
            transform: 'translateX(-50%)', zIndex: 50,
            padding: '8px 14px', borderRadius: 999,
            background: 'rgba(28,23,16,0.92)', color: '#fff',
            fontSize: 12, fontWeight: 500,
            boxShadow: 'var(--sh-2)',
            display: 'flex', alignItems: 'center', gap: 6,
            whiteSpace: 'nowrap',
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: 99, background: toast.color,
            }} />
            {toast.text}
          </div>
        )}

        {!top ? (
          <EmptyDeck
            onRestart={restart}
            filtered={brandFilter != null}
            onClearFilter={() => pickBrand(null)}
          />
        ) : (
          <>
            {/* card behind +2 */}
            {next2 && <BackdropCard drink={next2} depth={2} />}
            {/* card behind +1 */}
            {next1 && <BackdropCard drink={next1} depth={1} />}
            {/* top card */}
            <TopCard
              drink={top}
              drag={drag}
              exit={exit}
              onPointerDown={onPointerDown}
              onPointerMove={onPointerMove}
              onPointerUp={onPointerUp}
              onPointerCancel={onPointerCancel}
              onTap={() => onOpenDrink?.(top)}
            />
          </>
        )}
      </div>

      {/* Action buttons */}
      <div style={{
        padding: '20px 16px 16px',
        display: 'flex', justifyContent: 'center', gap: 28,
      }}>
        <ActionButton
          icon={<IconX size={26} color="var(--ink-3)" stroke={2.4} />}
          bg="var(--surface)" disabled={!top || !!exit}
          onClick={() => triggerAction('dislike')}
          size={56}
        />
        <ActionButton
          icon={<IconClock size={30} color="var(--brand-yellow-ink)" stroke={2.2} />}
          bg="var(--brand-yellow-soft)" disabled={!top || !!exit}
          onClick={() => triggerAction('maybe')}
          size={68}
          ring="var(--brand-yellow)"
          label="再看看"
        />
        <ActionButton
          icon={<IconHeart size={26} color="#fff" fill="#fff" stroke={0} />}
          bg="#F472A8" disabled={!top || !!exit}
          onClick={() => triggerAction('like')}
          size={56}
        />
      </div>
    </div>
  );
}

// ── Header ──
// 注意：右上角不放任何自定义按钮，留给微信小程序原生胶囊 (···/○)。
function HomeHeader() {
  return (
    <div style={{
      padding: '52px 16px 8px',
      display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <img
        src="https://hkr2ch9lfbyqaovx.public.blob.vercel-storage.com/avatars/flat-02.png"
        alt="头像"
        style={{
          width: 36, height: 36, borderRadius: 999,
          objectFit: 'cover', background: 'var(--sunken)',
          boxShadow: 'var(--sh-1)',
        }}
      />
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-1)', lineHeight: 1.2 }}>
          Hi，YOYO
        </span>
        <span style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>
          今天想喝点啥？
        </span>
      </div>
    </div>
  );
}

// ── Backdrop card (peek under the top card) ──
function BackdropCard({ drink, depth }) {
  const scale = 1 - depth * 0.05;
  const offsetY = depth * 10;
  return (
    <div style={{
      position: 'absolute', inset: 0,
      transform: `translateY(${offsetY}px) scale(${scale})`,
      transformOrigin: 'top center',
      background: 'var(--surface)', borderRadius: 28,
      boxShadow: 'var(--sh-1)',
      opacity: 1 - depth * 0.25,
      zIndex: 10 - depth,
      pointerEvents: 'none',
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(180deg, ${drink.colorA}55, ${drink.colorA}22)`,
      }} />
    </div>
  );
}

// ── Top card ──
function TopCard({ drink, drag, exit, onTap, onPointerDown, onPointerMove, onPointerUp, onPointerCancel }) {
  let transform;
  let transition;
  let opacity = 1;
  if (exit) {
    if (exit.dir === 'down') {
      transform = `translate(0, 36px) rotate(0deg)`;
      transition = 'transform 280ms ease-out, opacity 280ms ease-out';
      opacity = 0;
    } else if (exit.dir === 'left') {
      transform = `translate(-460px, 0) rotate(-12deg)`;
      transition = 'transform 240ms ease-out, opacity 240ms ease-out';
      opacity = 0;
    } else if (exit.dir === 'right') {
      transform = `translate(460px, 0) rotate(12deg)`;
      transition = 'transform 240ms ease-out, opacity 240ms ease-out';
      opacity = 0;
    }
  } else if (drag.dragging) {
    const rot = drag.x * 0.04;
    transform = `translate(${drag.x}px, 0) rotate(${rot}deg)`;
    transition = 'none';
  } else {
    transform = 'translate(0, 0) rotate(0deg)';
    transition = 'transform 240ms ease-out, opacity 240ms ease-out';
  }

  // direction hint badge while dragging
  const swipeHintLabel = drag.dragging && Math.abs(drag.x) > 30
    ? (drag.x < 0 ? '下一杯 →' : '← 下一杯')
    : null;

  return (
    <div
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={onPointerUp}
      onPointerCancel={onPointerCancel}
      onClick={(e) => {
        // prevent tap-trigger after drag
        if (Math.abs(drag.x) > 6) return;
        onTap?.();
      }}
      style={{
        position: 'absolute', inset: 0,
        transform, transition, opacity,
        background: 'var(--surface)', borderRadius: 28,
        boxShadow: 'var(--sh-2)',
        zIndex: 20, overflow: 'hidden',
        touchAction: 'pan-y',
        cursor: drag.dragging ? 'grabbing' : 'grab',
        userSelect: 'none',
        display: 'flex', flexDirection: 'column',
      }}
    >
      {/* gradient art zone */}
      <div style={{
        position: 'relative', flex: 1,
        background: `linear-gradient(160deg, ${drink.colorA}, ${drink.colorA}cc 60%, ${drink.colorB}33)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden',
      }}>
        {/* decorative blob */}
        <div style={{
          position: 'absolute', top: -30, right: -30,
          width: 140, height: 140, borderRadius: '50%',
          background: 'rgba(255,255,255,0.35)',
        }} />
        <div style={{
          position: 'absolute', bottom: -50, left: -20,
          width: 110, height: 110, borderRadius: '50%',
          background: `${drink.colorB}33`,
        }} />

        {/* brand chip */}
        <div style={{
          position: 'absolute', top: 14, left: 14,
          padding: '5px 10px', borderRadius: 999,
          background: 'rgba(255,255,255,0.9)',
          fontSize: 11, fontWeight: 600, color: 'var(--ink-1)',
          boxShadow: 'var(--sh-1)',
        }}>
          {drink.brand}
        </div>
        {/* size chip */}
        <div style={{
          position: 'absolute', top: 14, right: 14,
          padding: '5px 10px', borderRadius: 999,
          background: 'rgba(255,255,255,0.7)',
          fontSize: 10, color: 'var(--ink-2)', fontWeight: 500,
        }}>
          {drink.size}
        </div>

        {/* cup */}
        <CupPlaceholder colorA={drink.colorA} colorB={drink.colorB} size={150} />

        {/* swipe hint */}
        {swipeHintLabel && (
          <div style={{
            position: 'absolute', bottom: 18, left: '50%',
            transform: 'translateX(-50%)',
            padding: '6px 12px', borderRadius: 999,
            background: 'rgba(28,23,16,0.85)', color: '#fff',
            fontSize: 11, fontWeight: 500,
          }}>
            {swipeHintLabel}
          </div>
        )}
      </div>

      {/* info zone */}
      <div style={{
        padding: '16px 18px 18px', background: 'var(--surface)',
      }}>
        <div style={{
          display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8,
        }}>
          {drink.tags.slice(0, 3).map(t => (
            <span key={t} className="chip" style={{
              fontSize: 10, padding: '3px 8px',
              background: 'var(--sunken)', color: 'var(--ink-2)',
              borderRadius: 999, fontWeight: 500,
            }}>{t}</span>
          ))}
        </div>
        <div style={{
          fontSize: 19, fontWeight: 700, color: 'var(--ink-1)',
          lineHeight: 1.25,
        }}>
          {drink.name}
        </div>

        {/* mini metrics */}
        <div style={{
          marginTop: 12, display: 'flex',
          alignItems: 'center', gap: 14,
        }}>
          <Metric label="kcal" value={drink.cal} color="var(--data-cal)" />
          <Divider />
          <Metric label="g 糖" value={drink.sugar} color="var(--data-sugar)" />
          <Divider />
          <Metric label="¥" value={drink.price} color="var(--ink-1)" prefix />
        </div>
      </div>
    </div>
  );
}

function Metric({ label, value, color, prefix }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 3 }}>
      {prefix && (
        <span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500 }}>{label}</span>
      )}
      <span style={{
        fontSize: 18, fontWeight: 700, color, fontFamily: 'var(--font-num)',
      }}>{value}</span>
      {!prefix && (
        <span style={{ fontSize: 10, color: 'var(--ink-3)', fontWeight: 500 }}>{label}</span>
      )}
    </div>
  );
}

function Divider() {
  return (
    <span style={{
      width: 1, height: 16, background: 'rgba(0,0,0,0.08)',
    }} />
  );
}

// ── Action button ──
function ActionButton({ icon, bg, ring, onClick, size = 56, disabled, label }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
      <button onClick={onClick} disabled={disabled} style={{
        width: size, height: size, borderRadius: '50%',
        background: bg,
        boxShadow: ring
          ? `0 0 0 3px ${ring}40, var(--sh-2)`
          : 'var(--sh-2)',
        border: '0.5px solid rgba(0,0,0,0.04)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        opacity: disabled ? 0.5 : 1,
        cursor: disabled ? 'not-allowed' : 'pointer',
        transition: 'transform 120ms ease',
      }}>
        {icon}
      </button>
      {label && (
        <span style={{ fontSize: 10, color: 'var(--ink-3)', fontWeight: 500 }}>
          {label}
        </span>
      )}
    </div>
  );
}

// ── Empty state ──
function EmptyDeck({ onRestart, filtered, onClearFilter }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      gap: 14, color: 'var(--ink-3)',
    }}>
      <div style={{
        width: 72, height: 72, borderRadius: '50%',
        background: 'var(--brand-yellow-soft)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <IconSparkle size={32} color="var(--brand-yellow-ink)" fill="var(--brand-yellow-ink)" stroke={0} />
      </div>
      <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink-1)' }}>
        {filtered ? '这家就这些啦' : '今天就这些啦'}
      </div>
      <div style={{ fontSize: 12 }}>
        {filtered ? '换个品牌再看看？' : '明天会有新的口味推给你'}
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        <button onClick={onRestart} style={{
          padding: '10px 18px', borderRadius: 999,
          background: 'var(--ink-1)', color: '#fff',
          fontSize: 13, fontWeight: 600,
        }}>
          再看一遍
        </button>
        {filtered && (
          <button onClick={onClearFilter} style={{
            padding: '10px 18px', borderRadius: 999,
            background: 'var(--surface)', color: 'var(--ink-1)',
            fontSize: 13, fontWeight: 600,
            boxShadow: 'inset 0 0 0 0.5px rgba(0,0,0,0.08)',
          }}>
            看全部
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen });
