/* global React, Icon, PageHeader, apiGet, relativeTime */
const { useState: useEboardState, useEffect: useEboardEffect, useMemo: useEboardMemo, useRef: useEboardRef } = React;

// === E-Board tickets =========================================================
// The e-board's Linear tickets (team CGAI-Eboard), read live through GET /api/eboard/tickets.
// Read-only: tickets are edited in Linear. Admin only. See tasks/eboard-tickets-page.md.
//
// A person picker (everyone on the Linear team), the order of work as a left-to-right tree
// (laid out on the server by buildExecutionFlow in lib/eboard-tickets.js; this file only
// draws it), then the tickets with their descriptions, grouped by when they're due. Picking
// a person narrows the list to their tickets and dims everyone else's in the tree, which
// keeps the path their work sits on. Hovering a ticket previews its path; clicking pins it.

const EBOARD_STALE_AFTER_MS = 60 * 1000; // matches the server's default LINEAR_CACHE_SECONDS
const EBOARD_SHOW_DONE_KEY = 'cgai.eboard.showDone';
const EBOARD_PERSON_KEY = 'cgai.eboard.person';
const EVERYONE = 'all';
const UNASSIGNED = 'unassigned';
const EBOARD_DUE_SOON_DAYS = 7;

function readEboardPref(key) {
  try { return window.localStorage.getItem(key); } catch { return null; }
}
function writeEboardPref(key, value) {
  try { window.localStorage.setItem(key, value); } catch { /* private window: keep it in memory */ }
}

const isDoneTicket = (ticket) => ticket.status.type === 'completed';

// Linear due dates are calendar days ("2026-11-06"), not instants, so compare them as local
// days; `new Date("2026-11-06")` would be midnight UTC, the evening before in Ithaca.
function daysUntilDue(ticket) {
  const match = String(ticket.dueDate || '').match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (!match) return null;
  const due = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return Math.round((due - today) / 86400000);
}

function shortDate(dueDate) {
  const [y, m, d] = dueDate.split('-').map(Number);
  return new Date(y, m - 1, d).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}

function dueLabel(ticket) {
  const days = daysUntilDue(ticket);
  if (days == null) return null;
  if (isDoneTicket(ticket)) return { text: shortDate(ticket.dueDate), tone: '' };
  if (days < 0) return { text: `Overdue ${-days}d`, tone: 'warn' };
  if (days === 0) return { text: 'Due today', tone: 'warn' };
  if (days === 1) return { text: 'Due tomorrow', tone: 'soon' };
  return { text: `Due ${shortDate(ticket.dueDate)}`, tone: days < EBOARD_DUE_SOON_DAYS ? 'soon' : '' };
}

// List groups, in display order.
const EBOARD_GROUPS = [
  { id: 'overdue', title: 'Overdue' },
  { id: 'soon', title: 'This week' },
  { id: 'later', title: 'Later' },
  { id: 'undated', title: 'No due date' },
  { id: 'done', title: 'Done' },
];
function groupFor(ticket) {
  if (isDoneTicket(ticket)) return 'done';
  const days = daysUntilDue(ticket);
  if (days == null) return 'undated';
  if (days < 0) return 'overdue';
  return days < EBOARD_DUE_SOON_DAYS ? 'soon' : 'later';
}

// Everything upstream and downstream of `focusId` along the flow's edges, and the edges
// that make up those two paths.
function pathThrough(focusId, edges) {
  const walk = (start, next) => {
    const seen = new Set();
    const stack = [start];
    while (stack.length) {
      const id = stack.pop();
      for (const other of next(id)) {
        if (!seen.has(other) && other !== start) { seen.add(other); stack.push(other); }
      }
    }
    return seen;
  };
  const upstream = walk(focusId, (id) => edges.filter((e) => e.to === id).map((e) => e.from));
  const downstream = walk(focusId, (id) => edges.filter((e) => e.from === id).map((e) => e.to));
  const nodes = new Set([focusId, ...upstream, ...downstream]);
  const onPath = (edge) => (upstream.has(edge.from) && (upstream.has(edge.to) || edge.to === focusId))
    || (downstream.has(edge.to) && (downstream.has(edge.from) || edge.from === focusId));
  return { nodes, onPath };
}

// Each person's colour on the tree (the dark canvas), in people order; unassigned work is
// the navy default. The pairs are a box fill and the ID text on it.
const OWNER_COLOURS = [
  { soft: '#372617', strong: '#e3a06a' }, // amber
  { soft: '#16301f', strong: '#6fcf97' }, // green
  { soft: '#2a2045', strong: '#b9a0ee' }, // violet
  { soft: '#123033', strong: '#5ec8c8' }, // teal
  { soft: '#3a1d26', strong: '#f08aa8' }, // rose
];
const UNASSIGNED_COLOUR = { soft: '#1b2947', strong: '#88a9ff' };

function ownerColours(people) {
  const byId = new Map(people.map((person, index) => [person.id, OWNER_COLOURS[index % OWNER_COLOURS.length]]));
  return (assigneeId) => (assigneeId && byId.get(assigneeId)) || UNASSIGNED_COLOUR;
}

function isPersonsTicket(ticket, personId) {
  if (personId === EVERYONE) return true;
  if (personId === UNASSIGNED) return !ticket.assigneeId;
  return ticket.assigneeId === personId;
}

// === Small pieces ============================================================
function EboardPill({ tone = '', children }) {
  return <span className={`eboard-pill ${tone}`}>{children}</span>;
}

function TicketPills({ ticket }) {
  const due = dueLabel(ticket);
  const status = ticket.status;
  return (
    <>
      {ticket.priority.value === 1 && <EboardPill tone="warn">Urgent</EboardPill>}
      {ticket.priority.value === 2 && <EboardPill tone="strong">High</EboardPill>}
      {status.type === 'started' && <EboardPill tone={/wait/i.test(status.name) ? 'wait' : 'live'}>{status.name}</EboardPill>}
      {status.type === 'completed' && <EboardPill>Done</EboardPill>}
      {due && <EboardPill tone={due.tone}>{due.text}</EboardPill>}
      {ticket.assignee && <span className="eboard-owner">{ticket.assignee}</span>}
    </>
  );
}

function StatusDot({ ticket }) {
  if (ticket.status.type !== 'started') return null;
  return <i className={`eboard-dot ${/wait/i.test(ticket.status.name) ? 'wait' : ''}`} title={ticket.status.name}/>;
}

// === Page ====================================================================
function EboardTickets() {
  const [board, setBoard] = useEboardState(null);
  const [status, setStatus] = useEboardState('loading');
  const [error, setError] = useEboardState('');
  // 0 = first load (the cached copy is fine); higher = Reload pressed (read Linear again).
  const [reloadToken, setReloadToken] = useEboardState(0);
  const [showDone, setShowDone] = useEboardState(() => readEboardPref(EBOARD_SHOW_DONE_KEY) === '1');
  const [selectedId, setSelectedId] = useEboardState(null);
  const [savedPersonId, setSavedPersonId] = useEboardState(() => readEboardPref(EBOARD_PERSON_KEY) || EVERYONE);

  useEboardEffect(() => {
    let cancelled = false;
    const load = (fresh) => apiGet(`/api/eboard/tickets${fresh ? '?fresh=1' : ''}`)
      .then((data) => {
        if (cancelled) return data;
        setBoard(data);
        setError('');
        setStatus('ready');
        return data;
      });
    load(reloadToken > 0)
      .then((data) => {
        // The server answers with its cached copy, which can be old after a quiet spell.
        // Paint it, then read Linear again so the page catches up on its own.
        const age = Date.now() - new Date(data?.fetchedAt || 0).getTime();
        if (!cancelled && reloadToken === 0 && age > EBOARD_STALE_AFTER_MS) return load(true);
        return null;
      })
      .catch((err) => {
        if (cancelled) return;
        setError(err.message || 'Could not load the e-board tickets.');
        setStatus('error');
      });
    return () => { cancelled = true; };
  }, [reloadToken]);

  const allTickets = board?.tickets || [];
  const tickets = useEboardMemo(() => allTickets.filter((t) => showDone || !isDoneTicket(t)), [allTickets, showDone]);
  const ticketsById = useEboardMemo(() => new Map(allTickets.map((t) => [t.id, t])), [allTickets]);
  const flow = (showDone ? board?.flows?.all : board?.flows?.open) || { columns: [], edges: [] };
  const people = board?.people || [];
  // A remembered person who has since left the team falls back to everyone.
  const personId = [EVERYONE, UNASSIGNED].includes(savedPersonId) || people.some((p) => p.id === savedPersonId)
    ? savedPersonId : EVERYONE;
  const personsTickets = useEboardMemo(() => tickets.filter((t) => isPersonsTicket(t, personId)), [tickets, personId]);
  const personsIds = useEboardMemo(
    () => (personId === EVERYONE ? null : new Set(personsTickets.map((t) => t.id))),
    [personId, personsTickets]
  );
  const selected = selectedId && tickets.some((t) => t.id === selectedId) ? selectedId : null;
  const doneCount = allTickets.filter(isDoneTicket).length;
  const colourFor = useEboardMemo(() => ownerColours(people), [people]);

  function choosePerson(id) {
    setSavedPersonId(id);
    writeEboardPref(EBOARD_PERSON_KEY, id);
  }

  const toggleSelected = (id) => setSelectedId((current) => (current === id ? null : id));

  // A click anywhere but a ticket (box or card), or Escape, lets go of the pinned one.
  // Dragging the canvas's resize grip ends in a click too, so a press that starts in the
  // grip's corner is let through.
  useEboardEffect(() => {
    if (!selected) return undefined;
    const GRIP = 24;
    let pressedOnGrip = false;
    const onPointerDown = (event) => {
      const box = event.target.closest?.('.eboard-flowbox');
      const r = box?.getBoundingClientRect();
      pressedOnGrip = Boolean(r && event.clientX > r.right - GRIP && event.clientY > r.bottom - GRIP);
    };
    const onClick = (event) => {
      if (pressedOnGrip) { pressedOnGrip = false; return; }
      if (event.target.closest?.('.eboard-node, .eboard-row')) return;
      setSelectedId(null);
    };
    const onKeyDown = (event) => { if (event.key === 'Escape') setSelectedId(null); };
    document.addEventListener('pointerdown', onPointerDown, true);
    document.addEventListener('click', onClick);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('pointerdown', onPointerDown, true);
      document.removeEventListener('click', onClick);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [selected]);

  function toggleShowDone(event) {
    setShowDone(event.target.checked);
    writeEboardPref(EBOARD_SHOW_DONE_KEY, event.target.checked ? '1' : '0');
  }

  const actions = (
    <>
      {board && <span className="eboard-synced">Updated {relativeTime(board.fetchedAt)}</span>}
      <button type="button" className="btn btn-ghost" disabled={status === 'loading'}
        onClick={() => { setStatus('loading'); setReloadToken((n) => n + 1); }}>
        {status === 'loading' && board ? 'Reloading…' : 'Reload'}
      </button>
      {board?.team?.url && (
        <a className="btn btn-ghost" href={board.team.url} target="_blank" rel="noopener noreferrer">
          <Icon name="external" size={14}/> Open in Linear
        </a>
      )}
    </>
  );

  return (
    <div className="eboard-page">
      <PageHeader eyebrow="E-Board · Linear" title="Tickets" actions={actions}/>

      {status === 'loading' && !board && <div className="eboard-notice">Loading tickets from Linear…</div>}
      {status === 'error' && (
        <div className="eboard-notice" role="alert"><b>Couldn’t load the tickets.</b> {error}</div>
      )}
      {board && !allTickets.length && <div className="eboard-notice">No tickets yet.</div>}

      {board && allTickets.length > 0 && (
        <>
          <EboardPeople people={people} tickets={tickets} personId={personId} onChoose={choosePerson}
            colourFor={colourFor} hasCritical={flow.critical?.length > 0}/>

          <section className="eboard-section" aria-label="Order of work">
            <EboardFlow flow={flow} ticketsById={ticketsById} selectedId={selected} onSelect={toggleSelected}
              personsIds={personsIds} colourFor={colourFor}/>
          </section>

          <section className="eboard-section" aria-label="Tickets">
            {doneCount > 0 && (
              <label className="eboard-toggle">
                <input type="checkbox" checked={showDone} onChange={toggleShowDone}/> Show done ({doneCount})
              </label>
            )}
            <EboardList tickets={personsTickets} selectedId={selected} onSelect={toggleSelected}
              emptyText={personId === EVERYONE ? 'Nothing open.'
                : personId === UNASSIGNED ? 'Every ticket has an owner.'
                  : `No ${showDone ? '' : 'open '}tickets for ${people.find((p) => p.id === personId)?.name}.`}/>
          </section>
        </>
      )}
    </div>
  );
}

// === People ==================================================================
// One chip per person on the Linear team, with how many of the shown tickets are theirs.
// Each chip's dot is that person's colour on the tree, so the row doubles as its key.
function EboardPeople({ people, tickets, personId, onChoose, colourFor, hasCritical }) {
  const count = (id) => tickets.filter((t) => isPersonsTicket(t, id)).length;
  const options = [
    { id: EVERYONE, name: 'Everyone' },
    ...people.map((person) => ({ ...person, colour: colourFor(person.id) })),
    { id: UNASSIGNED, name: 'Unassigned', colour: colourFor(null) },
  ];
  return (
    <div className="eboard-people-row">
      <section className="eboard-people" aria-label="Show tickets for">
        {options.map((option) => {
          const n = count(option.id);
          return (
            <button key={option.id} type="button" aria-pressed={option.id === personId}
              className={`eboard-person ${option.id === personId ? 'on' : ''} ${n ? '' : 'is-empty'}`}
              onClick={() => onChoose(option.id)}>
              {option.colour && <i className="eboard-person-dot" style={{ background: option.colour.strong }}/>}
              {option.name}<span className="eboard-person-count">{n}</span>
            </button>
          );
        })}
      </section>
      {hasCritical && <span className="eboard-key"><i/>Critical path</span>}
    </div>
  );
}

// === List ====================================================================
function EboardList({ tickets, selectedId, onSelect, emptyText }) {
  const groups = EBOARD_GROUPS
    .map((group) => ({ ...group, tickets: tickets.filter((t) => groupFor(t) === group.id) }))
    .filter((group) => group.tickets.length);
  if (!groups.length) return <p className="eboard-none">{emptyText}</p>;
  return (
    <div className="eboard-groups">
      {groups.map((group) => (
        <div key={group.id} className={`eboard-group ${group.id}`}>
          <div className="eboard-group-head">
            <h3>{group.title}</h3>
            <span>{group.tickets.length}</span>
          </div>
          <ol className="eboard-rows">
            {group.tickets.map((ticket) => (
              <EboardRow key={ticket.id} ticket={ticket} selected={ticket.id === selectedId} onSelect={onSelect}/>
            ))}
          </ol>
        </div>
      ))}
    </div>
  );
}

function EboardRow({ ticket, selected, onSelect }) {
  return (
    // The row is clickable for the mouse; the title button is the keyboard control.
    <li className={`eboard-row ${selected ? 'sel' : ''} ${isDoneTicket(ticket) ? 'is-done' : ''}`} onClick={() => onSelect(ticket.id)}>
      <div className="eboard-row-title">
        <span className="eboard-id"><StatusDot ticket={ticket}/>{ticket.id}</span>
        <button type="button" className="eboard-row-button" aria-pressed={selected}
          onClick={(event) => { event.stopPropagation(); onSelect(ticket.id); }}>
          {ticket.title}
        </button>
        <TicketPills ticket={ticket}/>
        <a className="eboard-row-open" href={ticket.url} target="_blank" rel="noopener noreferrer"
          aria-label={`Open ${ticket.id} in Linear`} title="Open in Linear"
          onClick={(event) => event.stopPropagation()}>
          <Icon name="external" size={13}/>
        </a>
      </div>
      {ticket.summary && <p className="eboard-why">{ticket.summary}</p>}
    </li>
  );
}

// === Flow ====================================================================
// Drawn like the OKRA build-order board: a dark canvas, one "Wave" column per step of the
// work, boxes coloured by owner, the critical path outlined, and quiet curves that turn
// blue along the focused ticket's path. The canvas is the page's width by default and can
// be resized from its bottom-right corner; boxes widen and columns spread to fill it,
// within bounds, and below the smallest sizes it scrolls.

const FLOW_PAD = 20;
const FLOW_TOP = 44; // room for the wave labels
const NODE_H = 68;
const ROW_GAP = 14;
const NODE_W = { min: 180, max: 300 };
const COL_GAP = { min: 44, max: 160 };
const FLOW_MAX_HEIGHT_SHARE = 0.75; // the starting height never takes more of the window than this

const clamp = (value, { min, max }) => Math.min(max, Math.max(min, value));

// The canvas height that shows every row without scrolling.
function flowHeight(columns) {
  const rows = Math.max(1, ...columns.map((ids) => ids.length));
  return FLOW_TOP + rows * NODE_H + (rows - 1) * ROW_GAP + FLOW_PAD;
}

function layoutFlow(columns, box) {
  const cols = Math.max(1, columns.length);
  const rows = Math.max(1, ...columns.map((ids) => ids.length));
  const availableWidth = Math.max(0, box.width - 2 * FLOW_PAD);
  const nodeW = clamp((availableWidth - (cols - 1) * COL_GAP.min) / cols, NODE_W);
  const colGap = cols > 1 ? clamp((availableWidth - cols * nodeW) / (cols - 1), COL_GAP) : 0;
  const treeWidth = cols * nodeW + (cols - 1) * colGap;
  const width = Math.max(box.width, treeWidth + 2 * FLOW_PAD);
  const height = Math.max(box.height, flowHeight(columns));
  const left = FLOW_PAD + Math.max(0, (width - 2 * FLOW_PAD - treeWidth) / 2);
  const tallest = rows * NODE_H + (rows - 1) * ROW_GAP;
  const position = new Map();
  const waves = [];
  columns.forEach((ids, column) => {
    const x = left + column * (nodeW + colGap);
    waves.push(x);
    // Shorter columns sit level with the middle of the tallest one, as on the OKRA board.
    const top = FLOW_TOP + (tallest - (ids.length * NODE_H + (ids.length - 1) * ROW_GAP)) / 2;
    ids.forEach((id, row) => position.set(id, { x, y: top + row * (NODE_H + ROW_GAP) }));
  });
  return { position, waves, width, height, nodeW };
}

function flowCurve(a, b, nodeW) {
  const x1 = a.x + nodeW;
  const y1 = a.y + NODE_H / 2;
  const x2 = b.x;
  const y2 = b.y + NODE_H / 2;
  const bend = Math.max(40, (x2 - x1) * 0.45);
  return `M${x1},${y1} C${x1 + bend},${y1} ${x2 - bend},${y2} ${x2},${y2}`;
}

function EboardFlow({ flow, ticketsById, selectedId, onSelect, personsIds = null, colourFor }) {
  const [hoverId, setHoverId] = useEboardState(null);
  const [box, setBox] = useEboardState({ width: 0, height: 0 });
  const boxRef = useEboardRef(null);
  // Set once: after that the height is whatever the viewer drags it to. React leaves the
  // inline height alone while this value doesn't change, so a drag isn't undone on re-render.
  const [initialHeight] = useEboardState(() => Math.round(Math.min(
    flowHeight(flow.columns) + 2, // + the border
    (window.innerHeight || 800) * FLOW_MAX_HEIGHT_SHARE,
  )));

  // Relayout whenever the canvas changes size: a window resize or the viewer dragging it.
  useEboardEffect(() => {
    const element = boxRef.current;
    if (!element || typeof ResizeObserver === 'undefined') return undefined;
    const observer = new ResizeObserver(() => {
      setBox((current) => (current.width === element.clientWidth && current.height === element.clientHeight
        ? current
        : { width: element.clientWidth, height: element.clientHeight }));
    });
    observer.observe(element);
    return () => observer.disconnect();
  }, []);

  const layout = useEboardMemo(() => layoutFlow(flow.columns, box), [flow, box]);
  const critical = flow.critical || [];
  const criticalEdges = new Set(critical.slice(1).map((id, index) => `${critical[index]}>${id}`));
  const focusId = hoverId || selectedId;
  const path = focusId ? pathThrough(focusId, flow.edges) : null;
  const selectedX = layout.position.get(selectedId)?.x;

  // When the tree is wider than the canvas (a phone), keep the selected ticket in view.
  useEboardEffect(() => {
    const element = boxRef.current;
    if (!element || selectedX == null || element.scrollWidth <= element.clientWidth) return;
    element.scrollTo({ left: Math.max(0, selectedX + layout.nodeW / 2 - element.clientWidth / 2), behavior: 'smooth' });
  }, [selectedX, layout.nodeW]);

  return (
    <div className="eboard-flowbox" ref={boxRef} style={{ height: initialHeight }}>
      <div className={`eboard-flow ${path ? 'focus' : ''}`}
        style={{ width: layout.width, height: layout.height }} onMouseLeave={() => setHoverId(null)}>
        {layout.waves.map((x, index) => (
          <div key={index} className="eboard-wave" style={{ left: x }}>Wave {index + 1}</div>
        ))}
        <svg width={layout.width} height={layout.height} viewBox={`0 0 ${layout.width} ${layout.height}`} aria-hidden="true">
          {flow.edges.map((edge) => {
            const a = layout.position.get(edge.from);
            const b = layout.position.get(edge.to);
            if (!a || !b) return null;
            const key = `${edge.from}>${edge.to}`;
            const lit = path?.onPath(edge);
            const others = personsIds && !personsIds.has(edge.from) && !personsIds.has(edge.to);
            return (
              <path key={key} d={flowCurve(a, b, layout.nodeW)}
                className={`eboard-edge ${criticalEdges.has(key) ? 'crit' : ''} ${lit ? 'hl' : ''} ${others ? 'is-other' : ''}`}/>
            );
          })}
        </svg>
        {[...layout.position.entries()].map(([id, { x, y }]) => {
          const ticket = ticketsById.get(id);
          if (!ticket) return null;
          const due = dueLabel(ticket);
          const colour = colourFor(ticket.assigneeId);
          const classes = ['eboard-node'];
          if (path?.nodes.has(id)) classes.push('hl');
          if (id === selectedId) classes.push('sel');
          if (critical.includes(id)) classes.push('crit');
          if (isDoneTicket(ticket)) classes.push('is-done');
          if (personsIds && !personsIds.has(id)) classes.push('is-other');
          return (
            <button key={id} type="button" className={classes.join(' ')}
              style={{ left: x, top: y, width: layout.nodeW, height: NODE_H, '--owner-soft': colour.soft, '--owner-strong': colour.strong }}
              aria-pressed={id === selectedId} title={ticket.summary || ticket.title}
              aria-label={`${id} ${ticket.title}, ${ticket.assignee || 'unassigned'}${due ? `, ${due.text}` : ''}${critical.includes(id) ? ', on the critical path' : ''}`}
              onMouseEnter={() => setHoverId(id)} onFocus={() => setHoverId(id)} onBlur={() => setHoverId(null)}
              onClick={() => onSelect(id)}>
              <span className="eboard-node-top">
                <span className="eboard-id"><StatusDot ticket={ticket}/>{id}</span>
                {due && <span className={`eboard-node-due ${due.tone}`}>{due.text.replace(/^Due /, '')}</span>}
              </span>
              <span className="eboard-node-title">{ticket.title}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}
