/* Step 2 - Impact × Complexity matrix (free placement) */
const { useState, useRef } = React;

const SEED = [
{ id: "s1", text: "Reduce manual sorting of citizen complaints" },
{ id: "s2", text: "Forecast tax revenue more accurately" },
{ id: "s3", text: "Detect anomalies in procurement spend" },
{ id: "s4", text: "Search internal policies in plain language" }];


// Visual backdrop only - quadrant tints + guidance. Chips float on top.
const CELLS = {
  tl: { label: "High impact, low complexity", recommendation: "Focus here first.", color: "tl" },
  tr: { label: "High impact, high complexity", recommendation: "Worth scoping but only with strong technical support.", color: "tr" },
  bl: { label: "Low impact, low complexity", recommendation: "Quick wins that can be revisited later.", color: "bl" },
  br: { label: "Low impact, High complexity", recommendation: "Avoid for now. Not worth the effort.", color: "br" }
};

// Map an idea's x/y (% of board) to the quadrant it currently sits in, for colour.
const quadrantOf = (x, y) => (y < 50 ? (x < 50 ? "tl" : "tr") : (x < 50 ? "bl" : "br"));
const clamp = (n) => Math.max(5, Math.min(95, n));

function Matrix() {
  // Each idea: {id, text, placed: bool, x, y}  (x,y are % of the plot area)
  const [ideas, setIdeas] = useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("igc.matrix.v2") || "null");
      if (Array.isArray(saved)) return saved;
    } catch {}
    // Migrate old quadrant-based layout if present
    try {
      const old = JSON.parse(localStorage.getItem("igc.matrix.v1") || "null");
      if (Array.isArray(old)) {
        const SPOT = { tl: [25, 25], tr: [75, 25], bl: [25, 75], br: [75, 75] };
        return old.map((i) => {
          const spot = SPOT[i.cell];
          return spot ?
          { id: i.id, text: i.text, placed: true, x: spot[0], y: spot[1] } :
          { id: i.id, text: i.text, placed: false, x: 50, y: 50 };
        });
      }
    } catch {}
    return SEED.map((s) => ({ ...s, placed: false, x: 50, y: 50 }));
  });
  const [draft, setDraft] = useState("");
  const [overBoard, setOverBoard] = useState(false);
  const [overPool, setOverPool] = useState(false);
  const dragId = useRef(null);
  const grabOffset = useRef({ x: 0, y: 0 });
  const plotRef = useRef(null);

  const persist = (next) => {
    setIdeas(next);
    localStorage.setItem("igc.matrix.v2", JSON.stringify(next));
  };

  const addIdea = () => {
    if (!draft.trim()) return;
    const id = "u" + Date.now();
    persist([...ideas, { id, text: draft.trim(), placed: false, x: 50, y: 50 }]);
    setDraft("");
  };
  const removeIdea = (id) => persist(ideas.filter((i) => i.id !== id));

  const onDragStart = (id) => (e) => {
    dragId.current = id;
    const r = e.currentTarget.getBoundingClientRect();
    grabOffset.current = { x: e.clientX - (r.left + r.width / 2), y: e.clientY - (r.top + r.height / 2) };
    e.dataTransfer.effectAllowed = "move";
    try {e.dataTransfer.setData("text/plain", id);} catch {}
  };
  const onDragEnd = () => {dragId.current = null;setOverBoard(false);setOverPool(false);};

  const onBoardOver = (e) => {e.preventDefault();setOverBoard(true);};
  const onBoardLeave = () => setOverBoard(false);
  const onBoardDrop = (e) => {
    e.preventDefault();
    const id = dragId.current || e.dataTransfer.getData("text/plain");
    if (!id || !plotRef.current) return;
    const r = plotRef.current.getBoundingClientRect();
    const x = clamp(((e.clientX - grabOffset.current.x - r.left) / r.width) * 100);
    const y = clamp(((e.clientY - grabOffset.current.y - r.top) / r.height) * 100);
    persist(ideas.map((i) => i.id === id ? { ...i, placed: true, x, y } : i));
    setOverBoard(false);dragId.current = null;
  };

  const onPoolOver = (e) => {e.preventDefault();setOverPool(true);};
  const onPoolLeave = () => setOverPool(false);
  const onPoolDrop = (e) => {
    e.preventDefault();
    const id = dragId.current || e.dataTransfer.getData("text/plain");
    if (!id) return;
    persist(ideas.map((i) => i.id === id ? { ...i, placed: false } : i));
    setOverPool(false);dragId.current = null;
  };

  const pooled = ideas.filter((i) => !i.placed);
  const placed = ideas.filter((i) => i.placed);

  const Chip = ({ idea, floating }) => {
    const colorClass = floating ? quadrantOf(idea.x, idea.y) : "";
    const style = floating ? { left: idea.x + "%", top: idea.y + "%" } : undefined;
    return (
      <span className={"idea-chip " + colorClass + (floating ? " is-placed" : "")}
      style={style} draggable="true"
      onDragStart={onDragStart(idea.id)} onDragEnd={onDragEnd}>
        <svg className="grip" viewBox="0 0 10 10" fill="currentColor"><circle cx="2" cy="2" r="1" /><circle cx="2" cy="5" r="1" /><circle cx="2" cy="8" r="1" /><circle cx="6" cy="2" r="1" /><circle cx="6" cy="5" r="1" /><circle cx="6" cy="8" r="1" /></svg>
        {idea.text}
        <button className="remove" onClick={() => removeIdea(idea.id)} aria-label="Remove">×</button>
      </span>);

  };

  const Cell = ({ id }) => {
    const cfg = CELLS[id];
    return (
      <div className={"matrix-cell cell-" + id}>
        <span className="label">{cfg.label}</span>
        <span className="recommendation">{cfg.recommendation}</span>
      </div>);

  };

  return (
    <div className="matrix-shell">
      <aside className="idea-tray">
        <h4>Your ideas</h4>
        <div className="idea-input">
          <input type="text" placeholder="Add a problem to test…" value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && addIdea()} />
          <button className="btn btn--primary btn--sm" onClick={addIdea}>Add</button>
        </div>
        <div className={"idea-pool" + (overPool ? " is-over" : "")}
        onDragOver={onPoolOver} onDragLeave={onPoolLeave} onDrop={onPoolDrop}>
          {pooled.length === 0 ?
          <div className="empty-msg">All ideas placed. Drag any back here to reset.</div> :
          pooled.map((i) => <Chip key={i.id} idea={i} />)}
        </div>
        <p className="idea-tray-help">Drag chips anywhere on the matrix. If everything ends up in the centre you haven't prioritised, so push each idea toward the corner it most belongs in. Drag back here to unplace. Click × to remove.</p>
      </aside>

      <div>
        <div className="matrix-board">
          <div className="matrix-axis-y">Impact <span className="arrow">→</span></div>
          <div className="matrix-axis-x">Complexity <span className="arrow">→</span></div>
          <div className="matrix-plot" ref={plotRef}>
            <div className="matrix-grid">
              <Cell id="tl" /><Cell id="tr" />
              <Cell id="bl" /><Cell id="br" />
            </div>
            <div className={"matrix-float-layer" + (overBoard ? " is-over" : "")}
            onDragOver={onBoardOver} onDragLeave={onBoardLeave} onDrop={onBoardDrop}>
              {placed.map((i) => <Chip key={i.id} idea={i} floating={true} />)}
            </div>
          </div>
        </div>
        <div className="matrix-help">
          <div className="h-tl"><strong>Top-left</strong>High impact, low complexity. Start with these.</div>
          <div className="h-tr"><strong>TOP-RIGHT</strong>Big payoff but expensive and needs strong tech support.</div>
          <div className="h-bl"><strong>BOTTOM-LEFT </strong>Easy wins that could be useful later if you have some time.</div>
          <div className="h-br"><strong>BOTTOM-RIGHT</strong>Hard work for limited reward. Skip these.</div>
        </div>
      </div>
    </div>);

}

ReactDOM.createRoot(document.getElementById("matrix-root")).render(<Matrix />);
