/* global React, PR, PRCover */
const { useState, useMemo } = React;
const { I, Avatar, StagePill, DecisionPill, RiskDot, daysAgo, metricDelta } = PR;
const { Cover } = PRCover;

// ============ Table view ============
function TableView({ data, onOpen }) {
  const authorMap = Object.fromEntries(data.authors.map(a => [a.id, a]));
  const rows = data.hypotheses;

  return (
    <div className="table-wrap">
      <table className="table">
        <thead>
          <tr>
            <th style={{ width: 78 }}>ID</th>
            <th>Hypothesis</th>
            <th style={{ width: 130 }}>Stage</th>
            <th style={{ width: 130 }}>Genre</th>
            <th style={{ width: 80 }}>Author</th>
            <th style={{ width: 200 }}>Key Metric</th>
            <th style={{ width: 90 }}>Risk</th>
            <th style={{ width: 110 }}>Updated</th>
            <th style={{ width: 110 }}>Decision</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(h => {
            const a = authorMap[h.author];
            const m = metricDelta(h);
            const archived = h.decision === "kill";
            return (
              <tr key={h.id} className={archived ? "row-archived" : ""} onClick={() => onOpen && onOpen(h.id)}>
                <td><span className="cell-id">{h.id}</span></td>
                <td className="cell-title">
                  <div className="cell-title-row">
                    <Cover projectId={h.id} coverUrl={h.coverUrl} size="cell" />
                    <div>
                      <div>{h.title}</div>
                      {h.pivotedFrom && <div className="title-meta">↳ pivot from {h.pivotedFrom}</div>}
                      {h.pivotedTo   && <div className="title-meta">→ pivoted to {h.pivotedTo}</div>}
                    </div>
                  </div>
                </td>
                <td><StagePill stage={h.stage} stages={data.stages} /></td>
                <td>
                  <div className="tag-row">
                    {h.tags.slice(0, 2).map(t => <span key={t} className="tag" data-tag={t.toLowerCase().replace(/\s+/g, "-")}>{t}</span>)}
                  </div>
                </td>
                <td title={a.name}><Avatar author={a} /></td>
                <td>
                  <div className="cell-metric">
                    <div><span className="target">{h.keyMetric}</span></div>
                    <div>
                      <span className={m.className}>{m.display}</span>
                      <span className="target"> / {h.target}</span>
                    </div>
                  </div>
                </td>
                <td><RiskDot risk={h.risk} /></td>
                <td><span className="cell-date">{daysAgo(h.updated)}</span></td>
                <td><DecisionPill decision={h.decision} /></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ============ Kanban view ============
function KanbanView({ data, onOpen, onNew, onMove }) {
  const authorMap = Object.fromEntries(data.authors.map(a => [a.id, a]));
  const [dragOver, setDragOver] = useState(null);

  const byStage = useMemo(() => {
    const out = {};
    data.stages.forEach(s => out[s.id] = []);
    data.hypotheses.forEach(h => {
      if (h.decision === "kill") return;
      out[h.stage]?.push(h);
    });
    return out;
  }, [data]);

  const handleDragStart = (e, rndId) => {
    e.dataTransfer.setData("text/plain", rndId);
    e.dataTransfer.effectAllowed = "move";
  };

  const handleDragOver = (e, stageId) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
    setDragOver(stageId);
  };

  const handleDrop = (e, stageId) => {
    e.preventDefault();
    setDragOver(null);
    const rndId = e.dataTransfer.getData("text/plain");
    if (rndId && onMove) onMove(rndId, stageId);
  };

  return (
    <div className="kanban">
      {data.stages.map(s => {
        const items = byStage[s.id] || [];
        const isDropTarget = dragOver === s.id;
        return (
          <div
            key={s.id}
            className={"kanban-col" + (isDropTarget ? " drop-target" : "")}
            onDragOver={(e) => handleDragOver(e, s.id)}
            onDragLeave={() => setDragOver(null)}
            onDrop={(e) => handleDrop(e, s.id)}
          >
            <div className="kanban-col-head">
              <div className="kanban-title">
                <StagePill stage={s.id} stages={data.stages} />
                <span className="count">{items.length}</span>
              </div>
              <span className="add-btn" onClick={onNew}>{I.plus}</span>
            </div>
            {items.map(h => {
              const a = authorMap[h.author];
              const m = metricDelta(h);
              return (
                <div
                  key={h.id}
                  className="k-card"
                  draggable={true}
                  onDragStart={(e) => handleDragStart(e, h.id)}
                  onClick={() => onOpen && onOpen(h.id)}
                >
                  {h.coverUrl && (
                    <div className="k-card-cover" style={{ backgroundImage: `url(${h.coverUrl})` }} />
                  )}
                  <div className="k-card-head">
                    <span>{h.id}</span>
                    <span><span className={"risk-dot risk-" + h.risk}></span></span>
                  </div>
                  <div className="k-card-title">{h.title}</div>
                  <div className="k-card-tags" style={{ marginBottom: 8 }}>
                    {h.tags.map(t => <span key={t} className="tag" data-tag={t.toLowerCase().replace(/\s+/g, "-")}>{t}</span>)}
                  </div>
                  <div className="k-card-meta">
                    <span className="mono" style={{ fontSize: 11 }}>
                      {h.keyMetric}: <span className={m.className} style={{
                        color: m.className === "delta-good" ? "var(--scale-c)" : m.className === "delta-bad" ? "var(--kill)" : "var(--text-2)"
                      }}>{m.display}</span>
                    </span>
                    <Avatar author={a} />
                  </div>
                </div>
              );
            })}
            {items.length === 0 && (
              <div style={{ padding: "30px 8px", textAlign: "center", color: "var(--text-4)", fontSize: 12 }}>
                {s.desc}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ============ Cards view ============
function CardsView({ data, onOpen }) {
  const authorMap = Object.fromEntries(data.authors.map(a => [a.id, a]));
  const rows = data.hypotheses.filter(h => h.decision !== "kill");
  return (
    <div className="cards-grid">
      {rows.map(h => {
        const a = authorMap[h.author];
        const m = metricDelta(h);
        return (
          <div key={h.id} className="proj-card" onClick={() => onOpen && onOpen(h.id)}>
            <Cover projectId={h.id} coverUrl={h.coverUrl} size="thumb" />
            <div className="proj-card-head">
              <div>
                <div className="proj-card-id">{h.id} · {daysAgo(h.updated)}</div>
                <div className="proj-card-title">{h.title}</div>
              </div>
              <StagePill stage={h.stage} stages={data.stages} />
            </div>
            <div className="proj-card-loop">{h.coreLoop}</div>
            <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
              {h.tags.map(t => <span key={t} className="tag" data-tag={t.toLowerCase().replace(/\s+/g, "-")}>{t}</span>)}
            </div>
            <div className="proj-card-foot">
              <div className="metric-mini">
                <span className="label">{h.keyMetric}</span>{" · "}
                <span className={m.className} style={{
                  color: m.className === "delta-good" ? "var(--scale-c)" : m.className === "delta-bad" ? "var(--kill)" : "var(--text)"
                }}>{m.display}</span>
                <span className="label"> / {h.target}</span>
              </div>
              <Avatar author={a} />
            </div>
          </div>
        );
      })}
    </div>
  );
}

window.PRViews = { TableView, KanbanView, CardsView };
