/* ============================================================
   Fashion AI Workflow — Phase 05 · Parametric Pattern SVG
   ============================================================ */

const SIZE_PRESETS = {
  XS: { B: 80, W: 62, H: 86, BL: 38, SL: 56, SA: 1.0 },
  S:  { B: 84, W: 66, H: 90, BL: 39, SL: 57, SA: 1.0 },
  M:  { B: 88, W: 70, H: 94, BL: 40, SL: 58, SA: 1.0 },
  L:  { B: 92, W: 74, H: 98, BL: 41, SL: 59, SA: 1.2 },
  XL: { B: 96, W: 78, H: 102, BL: 42, SL: 60, SA: 1.2 },
};

function PatternSVG({ size, kind }) {
  // Simplified pattern math — illustrative.
  // Skirt: half-front + half-back, A-line.
  // Top: bodice half-front + half-back rectangle with armhole curve.
  const { B, W, H, BL, SA } = size;
  const sa = SA * 4;     // visual seam allowance in svg-units
  if (kind === "TOP" || kind === "BOTH") {
    // top occupies upper area
  }
  const skirtHip = H * 0.55;
  const skirtWaist = W * 0.55;
  const skirtLen = BL * 1.4;

  // svg viewbox in cm-ish units, 1 unit = 1 cm
  return (
    <svg viewBox="0 0 200 180" xmlns="http://www.w3.org/2000/svg" className="pattern-svg">
      <rect x="0" y="0" width="200" height="180" fill="#fff"/>

      {/* legend grid lines (very faint) */}
      <g stroke="#eee" strokeWidth="0.2">
        {Array.from({length: 9}, (_, i) => <line key={"v"+i} x1={i*25} y1="0" x2={i*25} y2="180"/>)}
        {Array.from({length: 8}, (_, i) => <line key={"h"+i} x1="0" y1={i*25} x2="200" y2={i*25}/>)}
      </g>

      {(kind === "TOP" || kind === "BOTH") && (
        <g transform="translate(10, 12)">
          {/* Front bodice half */}
          <g>
            {/* face fill */}
            <path d={`M 0 0 L ${B*0.28} 0 L ${B*0.30} ${BL*0.6} L ${W*0.28} ${BL*0.95} L 0 ${BL*0.95} Z`} fill="rgba(100,160,255,0.06)"/>
            {/* cut line w/ SA dashed */}
            <path d={`M -${sa} -${sa} L ${B*0.28+sa} -${sa} L ${B*0.30+sa} ${BL*0.6} L ${W*0.28+sa} ${BL*0.95+sa} L -${sa} ${BL*0.95+sa} Z`} fill="none" stroke="#bbb" strokeWidth="0.6" strokeDasharray="2 2"/>
            {/* stitch line */}
            <path d={`M 0 0 L ${B*0.28} 0 L ${B*0.30} ${BL*0.6} L ${W*0.28} ${BL*0.95} L 0 ${BL*0.95}`} fill="none" stroke="#111" strokeWidth="1.5"/>
            {/* fold line — left edge (CF) long-dash */}
            <path d={`M 0 0 L 0 ${BL*0.95}`} fill="none" stroke="#111" strokeWidth="2" strokeDasharray="6 4"/>
            {/* armhole notch */}
            <line x1={B*0.28} y1="0" x2={B*0.28+3} y2="0" stroke="#111" strokeWidth="1.5"/>
            {/* grain arrow */}
            <line x1={B*0.14} y1={BL*0.2} x2={B*0.14} y2={BL*0.75} stroke="#444" strokeWidth="1"/>
            <polygon points={`${B*0.14-1.5},${BL*0.22} ${B*0.14+1.5},${BL*0.22} ${B*0.14},${BL*0.18}`} fill="#444"/>
            <polygon points={`${B*0.14-1.5},${BL*0.73} ${B*0.14+1.5},${BL*0.73} ${B*0.14},${BL*0.77}`} fill="#444"/>
            <text x={B*0.14+3} y={BL*0.5} fontFamily="DM Mono, monospace" fontSize="3" fill="#222">GRAIN</text>
            {/* label */}
            <text x={B*0.14} y={BL*1.05} textAnchor="middle" fontFamily="DM Mono, monospace" fontSize="3.5" fill="#222">FRONT BODICE · ½</text>
          </g>
          {/* Back bodice half */}
          <g transform={`translate(${B*0.45}, 0)`}>
            <path d={`M 0 0 L ${B*0.27} 0 L ${B*0.30} ${BL*0.6} L ${W*0.28} ${BL*0.95} L 0 ${BL*0.95} Z`} fill="rgba(160,100,255,0.06)"/>
            <path d={`M 0 0 L ${B*0.27} 0 L ${B*0.30} ${BL*0.6} L ${W*0.28} ${BL*0.95} L 0 ${BL*0.95}`} fill="none" stroke="#111" strokeWidth="1.5"/>
            <path d={`M 0 0 L 0 ${BL*0.95}`} fill="none" stroke="#111" strokeWidth="2" strokeDasharray="6 4"/>
            <line x1={B*0.14} y1={BL*0.2} x2={B*0.14} y2={BL*0.75} stroke="#444" strokeWidth="1"/>
            <text x={B*0.14} y={BL*1.05} textAnchor="middle" fontFamily="DM Mono, monospace" fontSize="3.5" fill="#222">BACK BODICE · ½</text>
          </g>
        </g>
      )}

      {(kind === "SKIRT" || kind === "BOTH") && (
        <g transform={`translate(10, ${kind === "BOTH" ? 90 : 20})`}>
          {/* Skirt half-front */}
          <g>
            <path d={`M ${(skirtHip-skirtWaist)/2} 0 L ${(skirtHip+skirtWaist)/2} 0 L ${skirtHip} ${skirtLen*0.6} L 0 ${skirtLen*0.6} Z`} fill="rgba(100,160,255,0.06)"/>
            <path d={`M ${(skirtHip-skirtWaist)/2} 0 L ${(skirtHip+skirtWaist)/2} 0 L ${skirtHip} ${skirtLen*0.6} L 0 ${skirtLen*0.6} Z`} fill="none" stroke="#111" strokeWidth="1.5"/>
            {/* fold line — left side */}
            <path d={`M 0 0 L 0 ${skirtLen*0.6}`} fill="none" stroke="#111" strokeWidth="2" strokeDasharray="6 4"/>
            <text x={skirtHip*0.5} y={skirtLen*0.65 + 4} textAnchor="middle" fontFamily="DM Mono, monospace" fontSize="3.5" fill="#222">SKIRT FRONT · ½ · A-LINE</text>
          </g>
          {/* Skirt half-back */}
          <g transform={`translate(${skirtHip + 8}, 0)`}>
            <path d={`M ${(skirtHip-skirtWaist)/2} 0 L ${(skirtHip+skirtWaist)/2} 0 L ${skirtHip} ${skirtLen*0.6} L 0 ${skirtLen*0.6} Z`} fill="rgba(160,100,255,0.06)"/>
            <path d={`M ${(skirtHip-skirtWaist)/2} 0 L ${(skirtHip+skirtWaist)/2} 0 L ${skirtHip} ${skirtLen*0.6} L 0 ${skirtLen*0.6} Z`} fill="none" stroke="#111" strokeWidth="1.5"/>
            <path d={`M 0 0 L 0 ${skirtLen*0.6}`} fill="none" stroke="#111" strokeWidth="2" strokeDasharray="6 4"/>
            <text x={skirtHip*0.5} y={skirtLen*0.65 + 4} textAnchor="middle" fontFamily="DM Mono, monospace" fontSize="3.5" fill="#222">SKIRT BACK · ½</text>
          </g>
        </g>
      )}

      {/* 10cm scale bar bottom-right */}
      <g transform="translate(170, 170)">
        <line x1="0" y1="0" x2="20" y2="0" stroke="#111" strokeWidth="1"/>
        <line x1="0" y1="-2" x2="0" y2="2" stroke="#111" strokeWidth="1"/>
        <line x1="20" y1="-2" x2="20" y2="2" stroke="#111" strokeWidth="1"/>
        <text x="10" y="-3" textAnchor="middle" fontFamily="DM Mono, monospace" fontSize="3" fill="#222">10 CM</text>
      </g>
    </svg>
  );
}

function Phase05({ goPrev, goNew }) {
  const [sizeKey, setSizeKey] = React.useState("M");
  const [size, setSize]       = React.useState(SIZE_PRESETS.M);
  const [kind, setKind]       = React.useState("SKIRT");

  const setField = (k) => (v) => setSize({ ...size, [k]: parseFloat(v) || 0 });

  const pickSize = (k) => { setSizeKey(k); setSize(SIZE_PRESETS[k]); };

  const downloadSVG = () => {
    const svgEl = document.querySelector(".pattern-svg");
    if (!svgEl) return;
    const xml = new XMLSerializer().serializeToString(svgEl);
    const blob = new Blob([xml], { type: "image/svg+xml" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = `pattern-${kind.toLowerCase()}-${sizeKey}.svg`;
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  return (
    <>
      <PhaseHeader
        phase="05"
        title="Pattern Block SVG / 版型草圖"
        subtitle="Parametric skirt / top draft. Math prototype only — confirm with a pattern maker before cutting fabric."
      />

      <InfoBox phase="05" label="ATTENTION">
        This is a mathematical pattern prototype, not a production-ready cut sheet. Use as starting reference for your pattern maker.
      </InfoBox>

      {/* Size quick pick */}
      <div className="field" style={{ marginTop: 16 }}>
        <span className="field-label">SIZE QUICK PICK</span>
        <div className="chips">
          {["XS", "S", "M", "L", "XL"].map((k) => (
            <Chip
              key={k}
              label={k}
              active={sizeKey === k}
              onClick={() => pickSize(k)}
              color="#f87171" tint="rgba(248,113,113,0.14)" border="rgba(248,113,113,0.45)"
            />
          ))}
        </div>
      </div>

      {/* 6 measurement inputs */}
      <div className="meas-grid">
        {[
          ["B",  "胸圍 / BUST"],
          ["W",  "腰圍 / WAIST"],
          ["H",  "臀圍 / HIP"],
          ["BL", "衣長 / BODICE LEN"],
          ["SL", "袖長 / SLEEVE LEN"],
          ["SA", "縫份 / SEAM ALLOW"],
        ].map(([k, label]) => (
          <label key={k} className="meas-cell">
            <span className="meas-lbl">{label}</span>
            <input
              className="meas-in"
              type="number"
              step="0.1"
              value={size[k]}
              onChange={(e) => setField(k)(e.target.value)}
            />
          </label>
        ))}
      </div>

      {/* Pattern type chips */}
      <div className="field" style={{ marginTop: 16 }}>
        <span className="field-label">版型類型 / PATTERN TYPE</span>
        <div className="chips">
          {[["SKIRT","裙子"], ["TOP","上衣"], ["BOTH","兩件套"]].map(([k, zh]) => (
            <Chip
              key={k}
              label={`${k} · ${zh}`}
              active={kind === k}
              onClick={() => setKind(k)}
              color="#f87171" tint="rgba(248,113,113,0.14)" border="rgba(248,113,113,0.45)"
            />
          ))}
        </div>
      </div>

      {/* SVG preview */}
      <div className="svg-preview">
        <div className="svg-head">
          <span className="svg-title">PATTERN PREVIEW · {kind} · SIZE {sizeKey}</span>
          <button className="svg-dl" onClick={downloadSVG}>↓ DOWNLOAD SVG</button>
        </div>
        <div className="svg-stage">
          <PatternSVG size={size} kind={kind} />
        </div>
      </div>

      {/* Legend */}
      <div className="legend">
        <div className="legend-item"><span className="lg-key" style={{ background:"#111", height:"1.5px" }}/><span>STITCH</span></div>
        <div className="legend-item"><span className="lg-key" style={{ background:"transparent", border:"1px dashed #bbb", height:"0", borderTop:"1px dashed #bbb" }}/><span>CUT (SA)</span></div>
        <div className="legend-item"><span className="lg-key" style={{ background:"transparent", borderTop:"2px dashed #fff", borderImage:"none" }}><span style={{ display:"inline-block", borderTop:"2px dashed #e8e4dc", width:"100%" }}></span></span><span>FOLD CF/CB</span></div>
        <div className="legend-item"><span className="lg-key" style={{ background:"#444", height:"1px", width:"24px" }}/><span>GRAIN</span></div>
        <div className="legend-item"><span className="lg-key" style={{ background:"#111", height:"1.5px", width:"4px" }}/><span>NOTCH</span></div>
      </div>

      <InfoBox phase="03" label="REMINDER">
        Pattern math is illustrative. Always have a qualified pattern maker grade and confirm before fabric is cut.
      </InfoBox>

      <ActionBar columns="1fr 1fr">
        <ActionBtn label="← TECH FLAT" onClick={goPrev} />
        <ActionBtn label="✦ NEW BRIEF" phase="01" variant="primary" onClick={goNew} />
      </ActionBar>
    </>
  );
}

window.Phase05 = Phase05;
