// Yumla — Screens 1, 2, 3 (Home, Swipe, Thinking)
// Uses window.YUMLA.{DISHES, TIME_CONTEXTS}

const { useState, useEffect, useRef } = React;

// ── tokens ──────────────────────────────────────────────────────────
const T = {
  cream: "#FAF7F2",
  cream2: "#F3EEE5",
  ink: "#1F1F1F",
  ink2: "#3A3733",
  muted: "#8A8478",
  muted2: "#B8B0A1",
  line: "#EAE3D6",
  mango: "#FFB627",
  mangoDark: "#E89C12",
  white: "#FFFFFF",
};

const fontHead = `'Fraunces', 'Playfair Display', Georgia, serif`;
const fontUI = `'DM Sans', 'Inter', -apple-system, system-ui, sans-serif`;

// Tiny SVG icons (no external deps)
const Icon = ({ name, size = 18, color = "currentColor", stroke = 1.8 }) => {
  const c = color;
  const s = size;
  const props = { width: s, height: s, viewBox: "0 0 24 24", fill: "none", stroke: c, strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "arrow-right": return <svg {...props}><path d="M5 12h14M13 5l7 7-7 7" /></svg>;
    case "arrow-left": return <svg {...props}><path d="M19 12H5M11 5l-7 7 7 7" /></svg>;
    case "refresh": return <svg {...props}><path d="M21 12a9 9 0 1 1-3-6.7M21 4v5h-5" /></svg>;
    case "x": return <svg {...props}><path d="M18 6 6 18M6 6l12 12" /></svg>;
    case "heart": return <svg {...props}><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1-1.1a5.5 5.5 0 0 0-7.8 7.8l1 1L12 21l7.8-7.6 1-1a5.5 5.5 0 0 0 0-7.8z" /></svg>;
    case "check": return <svg {...props}><path d="M5 12l5 5L20 7" /></svg>;
    case "star": return <svg {...props} fill={c}><path d="M12 2l3 6.5L22 10l-5 4.8L18.5 22 12 18.3 5.5 22 7 14.8 2 10l7-1.5L12 2z" stroke="none" /></svg>;
    case "clock": return <svg {...props}><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></svg>;
    case "info": return <svg {...props}><circle cx="12" cy="12" r="9" /><path d="M12 8h.01M11 12h1v4h1" /></svg>;
    case "chevron-right": return <svg {...props}><path d="m9 6 6 6-6 6" /></svg>;
    default: return null;
  }
};

// ── Screen 1: Home ──────────────────────────────────────────────────
function HomeScreen({ ctx, variant = "default", onPick, onByMood, onPill }) {
  // variant: "default" | "questionFirst" | "minimal"
  return (
    <div style={homeStyles.root}>
      {/* Top bar */}
      <div style={homeStyles.topbar}>
        <span style={homeStyles.wordmark}>Yumla</span>
        <div style={homeStyles.avatar}>
          <img src="https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=120&h=120&fit=crop&crop=faces&q=80" alt="Aanya" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
        </div>
      </div>

      {/* Greeting */}
      <div style={homeStyles.greetWrap}>
        <div style={homeStyles.hi}>{ctx.greeting}</div>
        {variant === "default" && (
          <h1 style={homeStyles.hero}>{ctx.hero}</h1>
        )}
        {variant === "questionFirst" && (
          <>
            <div style={homeStyles.kicker}>{ctx.timeWord} ·</div>
            <h1 style={{ ...homeStyles.hero, fontSize: 42, lineHeight: 1.02 }}>
              {ctx.altHero1}
            </h1>
            <div style={homeStyles.heroSub}>{ctx.hero}</div>
          </>
        )}
        {variant === "minimal" && (
          <h1 style={{ ...homeStyles.hero, fontSize: 40, fontStyle: "italic" }}>
            {ctx.altHero2}
          </h1>
        )}
      </div>

      {/* Pills — horizontal scroll */}
      <div style={homeStyles.pillRow}>
        <div style={homeStyles.pillScroll}>
          {ctx.pills.map((p, i) => (
            <button key={i} style={homeStyles.pill} onClick={() => onPill && onPill(p)}>
              <span style={{ fontSize: 16 }}>{p.e}</span>
              <span>{p.label}</span>
            </button>
          ))}
          <div style={{ width: 8, flex: "0 0 8px" }} />
        </div>
      </div>

      {/* CTA */}
      <div style={homeStyles.ctaWrap}>
        <button style={homeStyles.cta} onClick={onPick}>
          <span>Just decide for me</span>
          <Icon name="arrow-right" size={20} color={T.ink} stroke={2.2} />
        </button>
        <button style={homeStyles.linkBtn} onClick={onByMood}>
          Or pick by mood →
        </button>
      </div>

      {/* Footer last-order */}
      <div style={homeStyles.lastOrder}>{ctx.lastOrder}</div>
    </div>
  );
}

const homeStyles = {
  root: {
    width: "100%", height: "100%", background: T.cream,
    display: "flex", flexDirection: "column",
    fontFamily: fontUI, color: T.ink,
    paddingTop: 44, // clear iOS status bar (9:41 / battery)
  },
  topbar: {
    display: "flex", alignItems: "center", justifyContent: "space-between",
    padding: "6px 22px 6px",
  },
  wordmark: { fontFamily: fontHead, fontSize: 22, fontWeight: 600, letterSpacing: -0.4, color: T.ink },
  avatar: {
    width: 36, height: 36, borderRadius: 999, background: T.cream2,
    overflow: "hidden",
    border: `1.5px solid ${T.line}`,
    flexShrink: 0,
  },
  greetWrap: {
    padding: "32px 22px 0",
  },
  hi: { fontSize: 14, color: T.muted, marginBottom: 14, fontWeight: 500 },
  kicker: { fontSize: 13, color: T.mangoDark, fontWeight: 600, letterSpacing: 0.4, textTransform: "uppercase", marginBottom: 6 },
  hero: {
    fontFamily: fontHead, fontWeight: 400, fontSize: 32,
    lineHeight: 1.12, letterSpacing: -0.6,
    color: T.ink, margin: 0, textWrap: "pretty",
  },
  heroSub: { marginTop: 14, fontSize: 15, color: T.muted, lineHeight: 1.45, maxWidth: 320 },
  pillRow: { marginTop: 28 },
  pillScroll: {
    display: "flex", gap: 8, overflowX: "auto",
    padding: "2px 22px", scrollbarWidth: "none",
    WebkitOverflowScrolling: "touch",
  },
  pill: {
    flex: "0 0 auto",
    display: "inline-flex", alignItems: "center", gap: 6,
    padding: "10px 14px", borderRadius: 999,
    background: T.white, border: `1px solid ${T.line}`,
    fontFamily: fontUI, fontSize: 14, color: T.ink, fontWeight: 500,
    cursor: "pointer", whiteSpace: "nowrap",
  },
  ctaWrap: {
    marginTop: "auto", padding: "16px 22px 8px",
    display: "flex", flexDirection: "column", alignItems: "center", gap: 14,
  },
  cta: {
    width: "100%", height: 60, borderRadius: 18,
    background: T.mango, border: "none",
    display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
    fontFamily: fontUI, fontSize: 17, fontWeight: 600, color: T.ink,
    cursor: "pointer",
    boxShadow: "0 8px 24px rgba(232, 156, 18, 0.25)",
  },
  linkBtn: {
    background: "transparent", border: "none",
    color: T.muted, fontSize: 14, fontFamily: fontUI, fontWeight: 500,
    cursor: "pointer",
  },
  lastOrder: {
    textAlign: "center", padding: "10px 22px 24px",
    fontSize: 12, color: T.muted2, fontWeight: 500,
  },
};

// ── Screen 2: Swipe deck ────────────────────────────────────────────
function SwipeScreen({ ctx, onBack, onDecide, onLove }) {
  const [idx, setIdx] = useState(0);
  const [dragX, setDragX] = useState(0);
  const [exiting, setExiting] = useState(null); // { dir: 'left'|'right'|'up' }
  const startX = useRef(null);
  const startY = useRef(null);
  const cards = ctx.deck;

  const advance = (dir) => {
    setExiting({ dir });
    setTimeout(() => {
      setExiting(null);
      setDragX(0);
      if (idx + 1 >= cards.length) {
        onDecide && onDecide();
      } else {
        setIdx(idx + 1);
      }
    }, 260);
  };

  const onPointerDown = (e) => {
    startX.current = e.clientX;
    startY.current = e.clientY;
  };
  const onPointerMove = (e) => {
    if (startX.current == null) return;
    setDragX(e.clientX - startX.current);
  };
  const onPointerUp = (e) => {
    if (startX.current == null) return;
    const dx = e.clientX - startX.current;
    const dy = e.clientY - startY.current;
    startX.current = null;
    startY.current = null;
    if (dy < -80 && Math.abs(dx) < 60) {
      onLove && onLove();
      advance("up");
    } else if (dx > 80) advance("right");
    else if (dx < -80) advance("left");
    else setDragX(0);
  };

  return (
    <div style={swipeStyles.root}>
      {/* Top bar */}
      <div style={swipeStyles.topbar}>
        <button style={swipeStyles.backBtn} onClick={onBack}>
          <Icon name="arrow-left" size={18} color={T.ink} />
        </button>
        <div style={swipeStyles.dots}>
          {cards.map((_, i) => (
            <div key={i} style={{
              ...swipeStyles.dot,
              background: i === idx ? T.ink : T.line,
              width: i === idx ? 18 : 6,
            }} />
          ))}
        </div>
        <button style={swipeStyles.skipBtn} onClick={onDecide}>
          Just decide →
        </button>
      </div>

      {/* Card stack */}
      <div style={swipeStyles.stage}>
        {cards.slice(idx, idx + 3).reverse().map((key, i, arr) => {
          const isTop = i === arr.length - 1;
          const dish = window.YUMLA.DISHES[key];
          const depth = arr.length - 1 - i;
          const baseScale = 1 - depth * 0.04;
          const baseY = depth * 14;
          let transform = `translateY(${baseY}px) scale(${baseScale})`;
          let opacity = 1;
          if (isTop) {
            const rot = (dragX / 18);
            if (exiting) {
              const tx = exiting.dir === "right" ? 500 : exiting.dir === "left" ? -500 : 0;
              const ty = exiting.dir === "up" ? -700 : 0;
              const r = exiting.dir === "right" ? 18 : exiting.dir === "left" ? -18 : 0;
              transform = `translate(${tx}px, ${ty}px) rotate(${r}deg)`;
              opacity = 0;
            } else {
              transform = `translate(${dragX}px, 0) rotate(${rot}deg)`;
            }
          }
          return (
            <div key={key + i} style={{
              ...swipeStyles.card,
              transform,
              opacity,
              transition: exiting && isTop ? "transform .26s ease, opacity .26s ease" : (dragX === 0 ? "transform .2s ease" : "none"),
              zIndex: 10 + i,
              pointerEvents: isTop ? "auto" : "none",
            }}
              onPointerDown={isTop ? onPointerDown : undefined}
              onPointerMove={isTop ? onPointerMove : undefined}
              onPointerUp={isTop ? onPointerUp : undefined}
              onPointerCancel={isTop ? onPointerUp : undefined}
            >
              <img src={dish.img} alt={dish.name} style={swipeStyles.cardImg} draggable={false} />
              <div style={swipeStyles.cardOverlay} />
              {/* swipe labels */}
              {isTop && (
                <>
                  <div style={{ ...swipeStyles.tag, ...swipeStyles.yes, opacity: Math.max(0, dragX / 100) }}>INTO IT</div>
                  <div style={{ ...swipeStyles.tag, ...swipeStyles.no, opacity: Math.max(0, -dragX / 100) }}>NOPE</div>
                </>
              )}
              <div style={swipeStyles.cardBody}>
                <div style={swipeStyles.cardName}>{dish.name}</div>
                <div style={swipeStyles.cardMeta}>{dish.cuisine} · {dish.mood}</div>
                <div style={swipeStyles.cardSub}>5 places near you</div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Buttons */}
      <div style={swipeStyles.btnRow}>
        <button style={{ ...swipeStyles.actionBtn, color: "#C44545" }} onClick={() => advance("left")}>
          <Icon name="x" size={22} color="#C44545" stroke={2.2} />
        </button>
        <button style={{ ...swipeStyles.actionBtn, ...swipeStyles.loveBtn }} onClick={() => { onLove && onLove(); advance("up"); }}>
          <Icon name="heart" size={22} color={T.white} stroke={2.2} />
        </button>
        <button style={{ ...swipeStyles.actionBtn, color: "#2D8A4E" }} onClick={() => advance("right")}>
          <Icon name="check" size={22} color="#2D8A4E" stroke={2.2} />
        </button>
      </div>
    </div>
  );
}

const swipeStyles = {
  root: { width: "100%", height: "100%", background: T.cream, display: "flex", flexDirection: "column", fontFamily: fontUI, color: T.ink },
  topbar: { display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 18px 8px" },
  backBtn: { width: 36, height: 36, borderRadius: 999, background: T.white, border: `1px solid ${T.line}`, display: "grid", placeItems: "center", cursor: "pointer" },
  dots: { display: "flex", gap: 5, alignItems: "center" },
  dot: { height: 6, borderRadius: 3, transition: "all .2s" },
  skipBtn: { background: "transparent", border: "none", color: T.muted, fontSize: 13, fontFamily: fontUI, fontWeight: 500, cursor: "pointer" },
  stage: { flex: 1, position: "relative", padding: "16px 18px", display: "grid", placeItems: "center" },
  card: {
    position: "absolute", width: "calc(100% - 36px)", height: "100%",
    borderRadius: 26, overflow: "hidden",
    background: T.white, boxShadow: "0 18px 40px rgba(31,31,31,0.12), 0 2px 6px rgba(31,31,31,0.06)",
    cursor: "grab", userSelect: "none", touchAction: "none",
    willChange: "transform",
  },
  cardImg: { position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", pointerEvents: "none" },
  cardOverlay: { position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(0,0,0,0) 45%, rgba(0,0,0,0.55) 100%)" },
  cardBody: { position: "absolute", left: 22, right: 22, bottom: 24, color: T.white },
  cardName: { fontFamily: fontHead, fontSize: 30, fontWeight: 500, letterSpacing: -0.4, lineHeight: 1.05, marginBottom: 6 },
  cardMeta: { fontSize: 14, opacity: 0.9, fontWeight: 500 },
  cardSub: { marginTop: 12, fontSize: 12, opacity: 0.8, letterSpacing: 0.3 },
  tag: {
    position: "absolute", top: 28, padding: "6px 14px",
    border: "3px solid", borderRadius: 8, fontWeight: 800, fontSize: 18, letterSpacing: 1.5,
  },
  yes: { right: 28, color: "#2D8A4E", borderColor: "#2D8A4E", transform: "rotate(8deg)" },
  no: { left: 28, color: "#C44545", borderColor: "#C44545", transform: "rotate(-8deg)" },
  btnRow: { display: "flex", gap: 18, justifyContent: "center", padding: "14px 0 22px" },
  actionBtn: {
    width: 56, height: 56, borderRadius: 999, background: T.white,
    border: `1px solid ${T.line}`, display: "grid", placeItems: "center",
    cursor: "pointer",
    boxShadow: "0 4px 14px rgba(31,31,31,0.06)",
  },
  loveBtn: { width: 64, height: 64, background: T.mango, border: "none", boxShadow: "0 8px 22px rgba(232, 156, 18, 0.35)" },
};

// ── Screen 3: Thinking ──────────────────────────────────────────────
function ThinkingScreen({ ctx, onDone }) {
  const [step, setStep] = useState(0);
  const lines = ctx.thinking;

  useEffect(() => {
    if (step >= lines.length) {
      const t = setTimeout(() => onDone && onDone(), 500);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setStep((s) => s + 1), 900);
    return () => clearTimeout(t);
  }, [step]);

  return (
    <div style={thinkStyles.root}>
      <div style={thinkStyles.center}>
        {/* Animated mark — bowl with breathing dot */}
        <div style={thinkStyles.markWrap}>
          <svg width="92" height="92" viewBox="0 0 92 92" style={{ display: "block" }}>
            {/* outer ring rotating */}
            <g style={{ transformOrigin: "46px 46px", animation: "yumla-spin 2.4s linear infinite" }}>
              <circle cx="46" cy="46" r="38" fill="none" stroke={T.mango} strokeWidth="2" strokeDasharray="3 8" opacity="0.6" />
            </g>
            {/* bowl */}
            <path d="M22 44 Q22 66 46 66 Q70 66 70 44 Z" fill={T.ink} />
            <ellipse cx="46" cy="44" rx="24" ry="4.5" fill={T.mango} />
            {/* steam — breathing */}
            <g style={{ animation: "yumla-steam 1.6s ease-in-out infinite" }}>
              <path d="M38 30 Q42 26 38 22 Q34 18 38 14" stroke={T.muted2} strokeWidth="2" fill="none" strokeLinecap="round" />
              <path d="M48 30 Q52 26 48 22 Q44 18 48 14" stroke={T.muted2} strokeWidth="2" fill="none" strokeLinecap="round" />
              <path d="M58 30 Q62 26 58 22 Q54 18 58 14" stroke={T.muted2} strokeWidth="2" fill="none" strokeLinecap="round" />
            </g>
          </svg>
        </div>

        {/* Lines */}
        <div style={thinkStyles.lines}>
          {lines.map((l, i) => (
            <div key={i} style={{
              ...thinkStyles.line,
              opacity: i < step ? 1 : (i === step ? 0.55 : 0.15),
              transform: `translateY(${i < step ? 0 : 6}px)`,
              transition: "all .35s ease",
            }}>
              {l}
            </div>
          ))}
        </div>

        <div style={thinkStyles.brand}>Yumla is deciding</div>
      </div>

      <style>{`
        @keyframes yumla-spin { to { transform: rotate(360deg); } }
        @keyframes yumla-steam {
          0%, 100% { opacity: 0.3; transform: translateY(2px); }
          50% { opacity: 0.8; transform: translateY(-2px); }
        }
      `}</style>
    </div>
  );
}

const thinkStyles = {
  root: { width: "100%", height: "100%", background: T.cream, display: "grid", placeItems: "center", fontFamily: fontUI, color: T.ink },
  center: { display: "flex", flexDirection: "column", alignItems: "center", padding: 36, textAlign: "center" },
  markWrap: { marginBottom: 36 },
  lines: { display: "flex", flexDirection: "column", gap: 10, alignItems: "center", minHeight: 110 },
  line: {
    fontFamily: fontHead, fontSize: 19, fontWeight: 400,
    color: T.ink, letterSpacing: -0.2, lineHeight: 1.3, maxWidth: 280,
    textWrap: "pretty",
  },
  brand: {
    marginTop: 36, fontSize: 11, letterSpacing: 2.5,
    color: T.muted2, textTransform: "uppercase", fontWeight: 600,
  },
};

window.YumlaScreens1 = { HomeScreen, SwipeScreen, ThinkingScreen, T, fontHead, fontUI, Icon };
