/* Save-the-Date image generator — draws on canvas, downloadable */
const { useState: gUseState, useEffect: gUseEffect, useRef: gUseRef } = React;

const GEN_THEMES = [
  { id: "marigold", name: "Marigold", bg: "#fbf3e1", primary: "#9d0d4a", accent: "#ef8c1a", text: "#1a0e2e" },
  { id: "peacock",  name: "Peacock",  bg: "#06727d", primary: "#fbf3e1", accent: "#ef8c1a", text: "#fbf3e1" },
  { id: "night",    name: "Night",    bg: "#1a0e2e", primary: "#ef8c1a", accent: "#fbf3e1", text: "#fbf3e1" },
  { id: "ivory",    name: "Ivory",    bg: "#fff8ec", primary: "#c2185b", accent: "#06727d", text: "#2b1a08" },
];

const GEN_MOTIFS = ["Mandala", "Marigold", "Paisley", "Peacock"];

function ImageGenerator({ dateLine, names }) {
  const [yourName, setYourName] = gUseState("");
  const [message, setMessage] = gUseState("Counting the days till we celebrate together");
  const [theme, setTheme] = gUseState(GEN_THEMES[0]);
  const [motif, setMotif] = gUseState("Mandala");
  const canvasRef = gUseRef(null);

  gUseEffect(() => {
    draw();
  }, [yourName, message, theme, motif]);

  const draw = () => {
    const c = canvasRef.current;
    if (!c) return;
    const W = 1080, H = 1350;
    c.width = W; c.height = H;
    const ctx = c.getContext("2d");
    ctx.fillStyle = theme.bg;
    ctx.fillRect(0, 0, W, H);

    // Border
    ctx.strokeStyle = theme.accent;
    ctx.lineWidth = 8;
    ctx.strokeRect(40, 40, W - 80, H - 80);
    ctx.strokeStyle = theme.primary;
    ctx.lineWidth = 2;
    ctx.strokeRect(56, 56, W - 112, H - 112);

    // Motif top
    drawMotif(ctx, motif, W / 2, 220, 280, theme);
    drawMotif(ctx, motif, W / 2, H - 220, 200, theme);

    // Eyebrow
    ctx.fillStyle = theme.accent;
    ctx.font = "600 22px JetBrains Mono, monospace";
    ctx.textAlign = "center";
    ctx.fillText("◆  S A V E   T H E   D A T E  ◆", W / 2, 430);

    // Names (huge serif)
    ctx.fillStyle = theme.primary;
    ctx.font = "400 120px Yatra One, serif";
    ctx.fillText(names[0] || "Madhurendra", W / 2, 580);

    // Amp
    ctx.fillStyle = theme.accent;
    ctx.font = "italic 80px Cormorant Garamond, serif";
    ctx.fillText("&", W / 2, 670);

    // Bride
    ctx.fillStyle = theme.primary;
    ctx.font = "400 120px Yatra One, serif";
    ctx.fillText(names[1] || "Diksha", W / 2, 790);

    // Divider
    ctx.strokeStyle = theme.accent;
    ctx.lineWidth = 1.5;
    ctx.beginPath();
    ctx.moveTo(W / 2 - 200, 850);
    ctx.lineTo(W / 2 + 200, 850);
    ctx.stroke();
    ctx.fillStyle = theme.accent;
    ctx.beginPath();
    ctx.arc(W / 2, 850, 6, 0, Math.PI * 2);
    ctx.fill();

    // Date
    ctx.fillStyle = theme.text;
    ctx.font = "italic 44px Cormorant Garamond, serif";
    ctx.fillText(dateLine || "December 12 & 13, 2026", W / 2, 920);

    // Venue line
    ctx.fillStyle = theme.text;
    ctx.font = "400 24px DM Sans, sans-serif";
    ctx.fillText("Kanpur • Uttar Pradesh", W / 2, 970);

    // Custom message wrap
    ctx.fillStyle = theme.text;
    ctx.font = "italic 32px Cormorant Garamond, serif";
    wrapText(ctx, `“${message}”`, W / 2, 1060, W - 240, 42);

    // signed by
    if (yourName.trim()) {
      ctx.fillStyle = theme.accent;
      ctx.font = "600 18px JetBrains Mono, monospace";
      ctx.fillText(`— from ${yourName.trim().toUpperCase()} —`, W / 2, H - 280);
    }

    // Corner ornaments
    drawCornerOrnament(ctx, 90, 90, theme.accent, 0);
    drawCornerOrnament(ctx, W - 90, 90, theme.accent, Math.PI / 2);
    drawCornerOrnament(ctx, 90, H - 90, theme.accent, -Math.PI / 2);
    drawCornerOrnament(ctx, W - 90, H - 90, theme.accent, Math.PI);
  };

  const handleDownload = () => {
    const c = canvasRef.current;
    if (!c) return;
    const link = document.createElement("a");
    link.download = `madhurendra-diksha-save-the-date.png`;
    link.href = c.toDataURL("image/png");
    link.click();
  };

  return (
    <div className="gen-wrap">
      <div className="gen-preview">
        <canvas ref={canvasRef} />
      </div>
      <div className="gen-controls">
        <div className="field">
          <label>Your name (optional)</label>
          <input
            type="text"
            placeholder="e.g. Aarav"
            value={yourName}
            onChange={(e) => setYourName(e.target.value)}
          />
        </div>
        <div className="field">
          <label>A short note</label>
          <input
            type="text"
            value={message}
            maxLength={90}
            onChange={(e) => setMessage(e.target.value)}
          />
        </div>
        <div className="field">
          <label>Theme</label>
          <div className="theme-row">
            {GEN_THEMES.map((t) => (
              <button
                key={t.id}
                className={`theme-pick ${theme.id === t.id ? "active" : ""}`}
                onClick={() => setTheme(t)}
                style={{
                  background: `linear-gradient(135deg, ${t.bg} 0%, ${t.bg} 45%, ${t.primary} 45%, ${t.primary} 75%, ${t.accent} 75%)`,
                }}
                aria-label={t.name}
              />
            ))}
          </div>
        </div>
        <div className="field">
          <label>Motif</label>
          <div className="motif-row">
            {GEN_MOTIFS.map((m) => (
              <button
                key={m}
                className={`motif-pick ${motif === m ? "active" : ""}`}
                onClick={() => setMotif(m)}
              >{m}</button>
            ))}
          </div>
        </div>
        <div style={{ marginTop: 20, display: "flex", gap: 10, flexWrap: "wrap" }}>
          <button className="btn-primary" onClick={handleDownload}>
            ↓  Download Card
          </button>
          <button
            className="btn-ghost"
            style={{ color: "#1a0e2e", borderColor: "#9d0d4a" }}
            onClick={() => {
              const c = canvasRef.current;
              if (!c || !navigator.share || !c.toBlob) return alert("Sharing not supported here — download instead.");
              c.toBlob((blob) => {
                const file = new File([blob], "save-the-date.png", { type: "image/png" });
                navigator.share({ files: [file], title: "Save the Date" }).catch(()=>{});
              });
            }}
          >
            ↗  Share
          </button>
        </div>
        <p style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 18, fontStyle: "italic", fontFamily: "Cormorant Garamond, serif" }}>
          Personalize your own save-the-date and share it with the family. Use it as your WhatsApp status, set it as your wallpaper, or print it!
        </p>
      </div>
    </div>
  );
}

/* ---- Canvas helpers ---- */
function wrapText(ctx, text, x, y, maxWidth, lineHeight) {
  const words = text.split(" ");
  let line = "";
  let lines = [];
  for (let n = 0; n < words.length; n++) {
    const test = line + words[n] + " ";
    if (ctx.measureText(test).width > maxWidth && n > 0) {
      lines.push(line.trim()); line = words[n] + " ";
    } else { line = test; }
  }
  lines.push(line.trim());
  lines.forEach((l, i) => ctx.fillText(l, x, y + i * lineHeight));
}

function drawCornerOrnament(ctx, x, y, color, rot) {
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(rot);
  ctx.strokeStyle = color;
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.arc(0, 0, 22, 0, Math.PI * 2);
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(0, 0, 8, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
  for (let i = 0; i < 6; i++) {
    const a = (i / 6) * Math.PI * 2;
    ctx.beginPath();
    ctx.arc(Math.cos(a) * 22, Math.sin(a) * 22, 3, 0, Math.PI * 2);
    ctx.fill();
  }
  ctx.restore();
}

function drawMotif(ctx, kind, cx, cy, size, theme) {
  ctx.save();
  ctx.translate(cx, cy);
  if (kind === "Mandala") {
    const rings = [
      { count: 12, r1: size * 0.15, r2: size * 0.36, color: theme.primary },
      { count: 18, r1: size * 0.38, r2: size * 0.5,  color: theme.accent },
    ];
    rings.forEach((r) => {
      for (let i = 0; i < r.count; i++) {
        const a = (i / r.count) * Math.PI * 2;
        ctx.strokeStyle = r.color;
        ctx.lineWidth = 2;
        ctx.beginPath();
        const x1 = Math.cos(a) * r.r1, y1 = Math.sin(a) * r.r1;
        const x2 = Math.cos(a) * r.r2, y2 = Math.sin(a) * r.r2;
        const mx = (x1 + x2) / 2 + Math.cos(a + Math.PI / 2) * 8;
        const my = (y1 + y2) / 2 + Math.sin(a + Math.PI / 2) * 8;
        const mx2 = (x1 + x2) / 2 - Math.cos(a + Math.PI / 2) * 8;
        const my2 = (y1 + y2) / 2 - Math.sin(a + Math.PI / 2) * 8;
        ctx.moveTo(x1, y1);
        ctx.quadraticCurveTo(mx, my, x2, y2);
        ctx.quadraticCurveTo(mx2, my2, x1, y1);
        ctx.stroke();
      }
    });
    ctx.fillStyle = theme.primary;
    ctx.beginPath(); ctx.arc(0, 0, 12, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = theme.accent;
    ctx.beginPath(); ctx.arc(0, 0, 5, 0, Math.PI * 2); ctx.fill();
  } else if (kind === "Marigold") {
    const petals = 16;
    for (let i = 0; i < petals; i++) {
      const a = (i / petals) * Math.PI * 2;
      ctx.fillStyle = theme.accent;
      ctx.beginPath();
      ctx.arc(Math.cos(a) * size * 0.28, Math.sin(a) * size * 0.28, size * 0.11, 0, Math.PI * 2);
      ctx.fill();
    }
    for (let i = 0; i < petals; i++) {
      const a = ((i + 0.5) / petals) * Math.PI * 2;
      ctx.fillStyle = theme.primary;
      ctx.beginPath();
      ctx.arc(Math.cos(a) * size * 0.18, Math.sin(a) * size * 0.18, size * 0.09, 0, Math.PI * 2);
      ctx.fill();
    }
    ctx.fillStyle = theme.primary;
    ctx.beginPath(); ctx.arc(0, 0, size * 0.10, 0, Math.PI * 2); ctx.fill();
  } else if (kind === "Paisley") {
    [-1, 1].forEach((dir) => {
      ctx.save();
      ctx.scale(dir, 1);
      ctx.translate(size * 0.18, 0);
      ctx.strokeStyle = theme.primary;
      ctx.lineWidth = 4;
      ctx.beginPath();
      ctx.moveTo(0, -size * 0.4);
      ctx.bezierCurveTo(size * 0.5, -size * 0.3, size * 0.55, size * 0.2, 0, size * 0.4);
      ctx.bezierCurveTo(-size * 0.15, size * 0.2, -size * 0.1, 0, size * 0.05, 0);
      ctx.stroke();
      ctx.strokeStyle = theme.accent;
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(0, -size * 0.32);
      ctx.bezierCurveTo(size * 0.38, -size * 0.22, size * 0.4, size * 0.16, 0.04 * size, size * 0.34);
      ctx.stroke();
      ctx.restore();
    });
  } else if (kind === "Peacock") {
    ctx.fillStyle = theme.primary; ctx.globalAlpha = 0.5;
    ctx.beginPath(); ctx.ellipse(0, 0, size * 0.32, size * 0.42, 0, 0, Math.PI * 2); ctx.fill();
    ctx.globalAlpha = 1;
    ctx.fillStyle = theme.accent;
    ctx.beginPath(); ctx.ellipse(0, -size * 0.04, size * 0.22, size * 0.30, 0, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = theme.text;
    ctx.beginPath(); ctx.ellipse(0, -size * 0.10, size * 0.13, size * 0.18, 0, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = theme.accent;
    ctx.beginPath(); ctx.ellipse(0, -size * 0.12, size * 0.07, size * 0.10, 0, 0, Math.PI * 2); ctx.fill();
  }
  ctx.restore();
}

window.ImageGenerator = ImageGenerator;
