/* 신도랑 라인업 보드 — 토글 / 카드 / 커넥터 */

const ACCENTS = ["#10b981","#9b5de5","#475569","#f4663a","#4f63e0","#0ea5e9","#eab308","#ec4899"];
const POS_CLASS = { "top-left":"tl", "top-right":"tr", "bottom-left":"bl", "bottom-right":"br" };
const ALL_POS = ["top-left","top-right","bottom-left","bottom-right"];

function Edit({ path, value, onEdit, editing, tag = "span", className = "", multiline = false }) {
  const Tag = tag;
  return (
    <Tag className={"editable " + className} contentEditable={editing} suppressContentEditableWarning
      onBlur={(e) => onEdit(path, multiline ? e.target.innerText : e.target.textContent)}
    >{value}</Tag>
  );
}
window.Edit = Edit;

/* ---------- Toggle ---------- */
function ModeToggle({ data, mode, setMode }) {
  const ref = React.useRef(null);
  const [pill, setPill] = React.useState({ left: 6, width: 0 });
  React.useLayoutEffect(() => {
    const root = ref.current; if (!root) return;
    const measure = () => {
      const btn = root.querySelector(`button[data-m="${mode}"]`);
      if (btn) setPill({ left: btn.offsetLeft, width: btn.offsetWidth });
    };
    measure();
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(measure);
    const t = setTimeout(measure, 150);
    return () => clearTimeout(t);
  }, [mode, data]);
  return (
    <div className="toggle" ref={ref}>
      <span className="pill" style={{ left: pill.left, width: pill.width }}></span>
      {["rental","purchase"].map((m) => (
        <button key={m} data-m={m} className={mode === m ? "on" : ""} onClick={() => setMode(m)}>
          {data.modes[m].label}
        </button>
      ))}
    </div>
  );
}

/* ---------- Corner card ---------- */
function CornerCard({ card, basePath, mode, editing, onEdit, refCb, onDelete }) {
  const cls = POS_CLASS[card.pos] || "tl";
  const align = (cls === "tr" || cls === "br") ? "flex-end" : "flex-start";
  return (
    <div className={"card-slot " + cls}>
    <div className={"card " + cls} ref={refCb}>
      {editing && (
        <div className="card-tools">
          <button className="del" title="삭제" onClick={() => onDelete(card.id)}>🗑</button>
        </div>
      )}
      <div className="accent-bar" style={{ background: card.accent }}></div>
      <Edit path={`${basePath}.category`} value={card.category} onEdit={onEdit} editing={editing}
        tag="p" className="cat" /> 
      <Edit path={`${basePath}.name`} value={card.name} onEdit={onEdit} editing={editing}
        tag="p" className="name" />
      {(card.desc || editing) && (
        <Edit path={`${basePath}.desc`} value={card.desc || (editing ? "설명 입력" : "")} onEdit={onEdit} editing={editing}
          tag="p" className="desc" multiline />
      )}
      <Edit path={`${basePath}.price`} value={card.price} onEdit={onEdit} editing={editing}
        tag="p" className="price" />
      {editing && (
        <div className="swatch-row" style={{ justifyContent: align }}>
          {ACCENTS.map((c) => (
            <span key={c} className={"swatch" + (c === card.accent ? " on" : "")} style={{ background: c }}
              onClick={() => onEdit(`${basePath}.accent`, c)}></span>
          ))}
        </div>
      )}
    </div>
    </div>
  );
}

/* ---------- Center card ---------- */
function CenterCard({ center, basePath, editing, onEdit, refCb, onOpen, onFloat }) {
  return (
    <div className="center" ref={refCb} onClick={() => { if (!editing) onOpen(); }}>
      {center.best && <div className="ribbon">BEST</div>}
      {center.recommended && <div className="badge-rec">추천</div>}
      <div className="top-rule"></div>
      <Edit path={`${basePath}.category`} value={center.category} onEdit={onEdit} editing={editing} tag="p" className="cat" />
      <Edit path={`${basePath}.name`} value={center.name} onEdit={onEdit} editing={editing} tag="p" className="name" />
      <Edit path={`${basePath}.price`} value={center.price} onEdit={onEdit} editing={editing} tag="p" className="price" />
      {!editing && <div className="hint">핵심 서비스 보기 →</div>}
      {center.floating && center.floating.enabled && (
        <div className="float-circle" onClick={(e) => { e.stopPropagation(); if (!editing) onFloat(); }}>
          <span className="plus">+</span>
          {(center.floating.lines || []).map((l, i) => <span key={i}>{l.replace(/^\+ ?/, "")}</span>)}
        </div>
      )}
    </div>
  );
}

/* ---------- Board ---------- */
function Board({ data, mode, editing, onEdit, onOpenPopup, onAddCard, onDeleteCard }) {
  const modeData = data.modes[mode];
  const boardRef = React.useRef(null);
  const centerRef = React.useRef(null);
  const cardRefs = React.useRef({});
  const [lines, setLines] = React.useState([]);
  const [labels, setLabels] = React.useState([]);
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 760);

  React.useEffect(() => {
    const onR = () => setIsMobile(window.innerWidth < 760);
    window.addEventListener("resize", onR);
    return () => window.removeEventListener("resize", onR);
  }, []);

  const compute = React.useCallback(() => {
    if (isMobile) { setLines([]); setLabels([]); return; }
    const board = boardRef.current, center = centerRef.current;
    if (!board || !center) return;
    const b = board.getBoundingClientRect();
    const cc = center.getBoundingClientRect();
    const nl = [], nlab = [];
    modeData.cards.forEach((card) => {
      const el = cardRefs.current[card.id];
      if (!el) return;
      const r = el.getBoundingClientRect();
      let x1, y1, x2, y2;
      const cls = POS_CLASS[card.pos];
      if (cls === "tl") { x1 = r.right - b.left; y1 = r.bottom - b.top; x2 = cc.left - b.left; y2 = cc.top - b.top; }
      else if (cls === "tr") { x1 = r.left - b.left; y1 = r.bottom - b.top; x2 = cc.right - b.left; y2 = cc.top - b.top; }
      else if (cls === "bl") { x1 = r.right - b.left; y1 = r.top - b.top; x2 = cc.left - b.left; y2 = cc.bottom - b.top; }
      else { x1 = r.left - b.left; y1 = r.top - b.top; x2 = cc.right - b.left; y2 = cc.bottom - b.top; }
      nl.push({ id: card.id, x1, y1, x2, y2 });
      if (card.connector) nlab.push({ id: card.id, x: (x1 + x2) / 2, y: (y1 + y2) / 2, t: card.connector });
    });
    setLines(nl); setLabels(nlab);
  }, [modeData, isMobile]);

  React.useLayoutEffect(() => {
    compute();
    const ro = new ResizeObserver(compute);
    if (boardRef.current) ro.observe(boardRef.current);
    const t = setTimeout(compute, 60);
    return () => { ro.disconnect(); clearTimeout(t); };
  }, [compute, editing, mode]);

  const byPos = {};
  modeData.cards.forEach((c) => { byPos[c.pos] = c; });

  if (isMobile) {
    return (
      <div className="board mobile" ref={boardRef}>
        <CenterCard center={modeData.center} basePath={`modes.${mode}.center`} editing={editing}
          onEdit={onEdit} refCb={(e) => (centerRef.current = e)} onOpen={onOpenPopup} onFloat={onOpenPopup} />
        {modeData.cards.map((card, i) => (
          <React.Fragment key={card.id}>
            {card.connector && <div className="conn-mobile">{card.connector}</div>}
            <CornerCard card={card} basePath={`modes.${mode}.cards.${i}`} mode={mode} editing={editing}
              onEdit={onEdit} refCb={(e) => (cardRefs.current[card.id] = e)} onDelete={onDeleteCard} />
          </React.Fragment>
        ))}
        {editing && modeData.cards.length < 4 && (
          <button className="add-card" style={{ position: "static", width: "100%" }}
            onClick={() => onAddCard(ALL_POS.find((p) => !byPos[p]))}>＋ 카드 추가</button>
        )}
      </div>
    );
  }

  return (
    <div className="board" ref={boardRef}>
      <svg className="svg-layer">
        {lines.map((l) => <line key={l.id} x1={l.x1} y1={l.y1} x2={l.x2} y2={l.y2} />)}
      </svg>
      {labels.map((l) => (
        <div className="conn-label" key={l.id} style={{ left: l.x, top: l.y }}>{l.t}</div>
      ))}

      {ALL_POS.map((pos) => {
        const card = byPos[pos];
        const idx = card ? modeData.cards.indexOf(card) : -1;
        if (card) {
          return <CornerCard key={pos} card={card} basePath={`modes.${mode}.cards.${idx}`} mode={mode}
            editing={editing} onEdit={onEdit} refCb={(e) => (cardRefs.current[card.id] = e)} onDelete={onDeleteCard} />;
        }
        if (editing) {
          return <button key={pos} className={"add-card " + POS_CLASS[pos]}
            style={posStyle(pos)} onClick={() => onAddCard(pos)}>＋ 카드 추가</button>;
        }
        return null;
      })}

      <CenterCard center={modeData.center} basePath={`modes.${mode}.center`} editing={editing}
        onEdit={onEdit} refCb={(e) => (centerRef.current = e)} onOpen={onOpenPopup} onFloat={onOpenPopup} />
    </div>
  );
}

function posStyle(pos) {
  const cls = POS_CLASS[pos];
  const s = { transform: "translateY(-50%)" };
  if (cls === "tl") { s.left = 0; s.top = "25%"; }
  if (cls === "tr") { s.right = 0; s.top = "25%"; }
  if (cls === "bl") { s.left = 0; s.top = "75%"; }
  if (cls === "br") { s.right = 0; s.top = "75%"; }
  return s;
}

window.Board = Board;
window.ModeToggle = ModeToggle;
