// DesignCanvas — renders the t-shirt artwork.
// Used both for on-screen preview and for hi-res PNG export (via scale prop).

const DesignCanvas = ({
  text = "JET LAG IS A PERSONALITY",
  layout = "stacked",
  font = "Special Elite",
  fontSize = 72,
  letterSpacing = 0,
  lineHeight = 1.1,
  inkColor = "#111111",
  rotation = 0,
  distress = 0.15,
  offsetX = 0,
  offsetY = 0,
  uploadedImage = null,    // data URL of uploaded image (logo etc.)
  imageScale = 0.6,        // 0..1 — fraction of canvas width
  imagePosition = "above", // "above" | "below" | "only"
  showFrame = false,
  width = 1500,
  height = 1800,
  scale = 1,
  background = "transparent",
}) => {
  // Split text by " / " for multi-line stacks; user can also use newlines
  const lines = text
    .split(/\s*\/\s*|\n/)
    .map(l => l.trim())
    .filter(Boolean);

  const cw = width * scale;
  const ch = height * scale;
  const fs = fontSize * scale;
  const ls = letterSpacing * scale;

  // Layout-specific renderer
  const renderLayout = () => {
    const baseStyle = {
      fontFamily: `"${font}", "Courier Prime", "Courier New", monospace`,
      fontSize: fs,
      letterSpacing: ls,
      lineHeight,
      color: inkColor,
      fontWeight: 400,
    };

    switch (layout) {
      case "centered":
        return (
          <div style={{ ...baseStyle, textAlign: "center" }}>
            {lines.join(" ")}
          </div>
        );

      case "stacked":
        return (
          <div style={{ ...baseStyle, textAlign: "center" }}>
            {lines.map((l, i) => (
              <div key={i}>{l}</div>
            ))}
          </div>
        );

      case "block": {
        // Big block, each line on its own row, justified width via tracking
        return (
          <div style={{ ...baseStyle, textAlign: "center", fontWeight: 700 }}>
            {lines.map((l, i) => (
              <div key={i} style={{ whiteSpace: "nowrap" }}>{l}</div>
            ))}
          </div>
        );
      }

      case "rule": {
        const ruleW = Math.max(2, fs * 0.025);
        return (
          <div style={{ ...baseStyle, textAlign: "center" }}>
            {lines.map((l, i) => (
              <React.Fragment key={i}>
                {i > 0 && (
                  <div
                    style={{
                      borderTop: `${ruleW}px solid ${inkColor}`,
                      width: "70%",
                      margin: `${fs * 0.15}px auto`,
                    }}
                  />
                )}
                <div>{l}</div>
              </React.Fragment>
            ))}
          </div>
        );
      }

      case "asterisk": {
        // ✶ asterisk separators between lines
        const all = [];
        lines.forEach((l, i) => {
          if (i > 0) all.push(<div key={`s-${i}`} style={{ fontSize: fs * 0.7, opacity: 0.85 }}>✶</div>);
          all.push(<div key={`l-${i}`}>{l}</div>);
        });
        return (
          <div style={{ ...baseStyle, textAlign: "center" }}>
            {all}
          </div>
        );
      }

      case "bracket": {
        return (
          <div style={{ ...baseStyle, textAlign: "center" }}>
            <div style={{ fontSize: fs * 0.6, marginBottom: fs * 0.1 }}>[ EST. NOW ]</div>
            {lines.map((l, i) => (
              <div key={i}>{l}</div>
            ))}
            <div style={{ fontSize: fs * 0.6, marginTop: fs * 0.1 }}>— FIELD NOTES —</div>
          </div>
        );
      }

      case "marquee": {
        // Single line wide with bullets, repeated
        const single = lines.join(" • ");
        return (
          <div style={{ ...baseStyle, textAlign: "center", whiteSpace: "nowrap", fontSize: fs * 0.85 }}>
            {`• ${single} • ${single} •`}
          </div>
        );
      }

      case "left": {
        return (
          <div style={{ ...baseStyle, textAlign: "left" }}>
            {lines.map((l, i) => (
              <div key={i}>
                <span style={{ opacity: 0.55, marginRight: fs * 0.3 }}>{String(i + 1).padStart(2, "0")}</span>
                {l}
              </div>
            ))}
          </div>
        );
      }

      case "stamp": {
        // Border thickness scales with font size, not canvas scale, so it stays
        // visually proportional whether rendered at 240px preview or 4500px print.
        const borderW = Math.max(4, fs * 0.05);
        return (
          <div
            style={{
              ...baseStyle,
              textAlign: "center",
              border: `${borderW}px double ${inkColor}`,
              padding: `${fs * 0.4}px ${fs * 0.7}px`,
              display: "inline-block",
            }}
          >
            {lines.map((l, i) => (
              <div key={i}>{l}</div>
            ))}
          </div>
        );
      }

      case "ticket": {
        return (
          <div style={{ ...baseStyle, textAlign: "center" }}>
            <div style={{ fontSize: fs * 0.45, letterSpacing: fs * 0.05, opacity: 0.7 }}>
              ── BOARDING PASS ──
            </div>
            <div style={{ marginTop: fs * 0.2 }}>
              {lines.map((l, i) => (
                <div key={i}>{l}</div>
              ))}
            </div>
            <div style={{ fontSize: fs * 0.4, marginTop: fs * 0.25, opacity: 0.7, fontFamily: "Courier Prime, monospace" }}>
              SEAT 24A · ZONE 3 · NO RETURN
            </div>
          </div>
        );
      }

      case "fill": {
        // Brand-defining "fill the canvas, one word per line" layout.
        // Auto-fits each word to the smaller of width fit / height fit, then
        // multiplies by userScale so the SIZE stepper still controls density.
        // 216 baseline = 100% (auto-fills canvas).
        const words = text
          .split(/\s*[\/·\n]\s*/)
          .flatMap(s => s.trim().split(/\s+/))
          .filter(Boolean)
          .map(w => w.toUpperCase());
        if (!words.length) return null;
        const userScale = Math.max(0.2, fontSize / 216);
        const targetW = cw * 1.0;
        const heightSlot = ch / words.length;
        const charFactor = 0.55;
        const sizes = words.map(w => {
          const widthFit = targetW / (Math.max(1, w.length) * charFactor);
          const heightFit = heightSlot * 0.98;
          return Math.min(widthFit, heightFit) * userScale;
        });
        return (
          <div style={{
            width: cw, height: ch,
            display: "flex", flexDirection: "column",
            alignItems: "center", justifyContent: "center",
            gap: 0,
          }}>
            {words.map((word, i) => (
              <div key={i} style={{
                fontFamily: `"${font}", "Courier Prime", monospace`,
                fontSize: sizes[i],
                color: inkColor,
                fontWeight: 400,
                letterSpacing: ls,
                lineHeight: 1,
                whiteSpace: "nowrap",
                textTransform: "uppercase",
              }}>
                {word}
              </div>
            ))}
          </div>
        );
      }

      default:
        return <div style={baseStyle}>{lines.join(" ")}</div>;
    }
  };

  // Distress overlay — subtle fragmented mask using radial gradients
  const distressOverlay = distress > 0 ? (
    <div
      style={{
        position: "absolute",
        inset: 0,
        pointerEvents: "none",
        backgroundImage: `
          radial-gradient(circle at 20% 30%, transparent 0, transparent ${1 + distress * 2}px, rgba(255,255,255,${distress * 0.6}) ${2 + distress * 3}px, transparent ${3 + distress * 4}px),
          radial-gradient(circle at 70% 60%, transparent 0, transparent ${1 + distress * 2}px, rgba(255,255,255,${distress * 0.5}) ${2 + distress * 3}px, transparent ${3 + distress * 4}px),
          radial-gradient(circle at 40% 80%, transparent 0, transparent ${1 + distress * 2}px, rgba(255,255,255,${distress * 0.4}) ${2 + distress * 3}px, transparent ${3 + distress * 4}px)
        `,
        backgroundSize: `${8 * scale}px ${8 * scale}px, ${11 * scale}px ${11 * scale}px, ${7 * scale}px ${7 * scale}px`,
        mixBlendMode: "screen",
        opacity: distress,
      }}
    />
  ) : null;

  return (
    <div
      data-design-canvas="true"
      style={{
        position: "relative",
        width: cw,
        height: ch,
        maxWidth: "100%",
        maxHeight: "100%",
        background,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        overflow: "hidden",
        boxSizing: "border-box",
      }}
    >
      {showFrame && (
        <div
          style={{
            position: "absolute",
            inset: `${cw * 0.08}px`,
            border: `1px dashed ${inkColor}33`,
            pointerEvents: "none",
          }}
        />
      )}
      {layout === "fill" && !uploadedImage ? (
        <div
          style={{
            transform: `translate(${offsetX}%, ${offsetY}%) rotate(${rotation}deg)`,
            width: cw,
            height: ch,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          {renderLayout()}
        </div>
      ) : uploadedImage && imagePosition === "only" ? (
        <div
          style={{
            transform: `translate(${offsetX}%, ${offsetY}%) rotate(${rotation}deg)`,
            width: cw,
            height: ch,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <img src={uploadedImage} alt="" style={{
            width: imageScale * cw,
            height: imageScale * ch,
            maxWidth: cw, maxHeight: ch,
            objectFit: "contain", display: "block",
          }} />
        </div>
      ) : (
        <div
          style={{
            transform: `translate(${offsetX}%, ${offsetY}%) rotate(${rotation}deg)`,
            maxWidth: "84%",
            padding: `0 ${cw * 0.06}px`,
            textAlign: "center",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            gap: cw * 0.02,
          }}
        >
          {uploadedImage && imagePosition === "above" && (
            <img src={uploadedImage} alt="" style={{
              width: imageScale * cw, height: "auto", maxHeight: ch * 0.5,
              objectFit: "contain", display: "block",
            }} />
          )}
          {imagePosition !== "only" && renderLayout()}
          {uploadedImage && imagePosition === "below" && (
            <img src={uploadedImage} alt="" style={{
              width: imageScale * cw, height: "auto", maxHeight: ch * 0.5,
              objectFit: "contain", display: "block",
            }} />
          )}
          {uploadedImage && imagePosition === "only" && (
            <img src={uploadedImage} alt="" style={{
              width: imageScale * cw, height: "auto", maxHeight: ch * 0.85,
              objectFit: "contain", display: "block",
            }} />
          )}
        </div>
      )}
      {distressOverlay}
    </div>
  );
};

window.DesignCanvas = DesignCanvas;
