// TaskEditView.jsx — Workspace task detail editor.
// Uses the same Material icons + status overlays as the rest of the product
// (MIcon + StatusOverlay are defined in Pipeline.jsx and exposed on window).

const TEV_TREE = [
  {
    id: 'g1', kind: 'folder', label: 'Component integration tests with real SignalR (3 of 3)',
    expanded: true, folderStatus: 'pulse-amber',
    children: [
      { id: 't1', kind: 'Extension', label: 'Add broadcast-trigger helper method', overlay: 'check-green' },
      { id: 't2', kind: 'Extension', label: 'Create SignalRIntegrationCompon...',  overlay: 'check-green' },
      { id: 't3', kind: 'Extension', label: 'Implement MergeQueuePanel SignalR tests', overlay: 'pulse-amber', selected: true },
      { id: 't4', kind: 'Description', label: 'Update SignalR testing documentation', overlay: 'dot-blue' },
    ],
  },
  {
    id: 'g2', kind: 'folder', label: 'Git-based workflows', expanded: true, folderStatus: 'dot-purple',
    children: [
      { id: 't5', kind: 'Extension', label: 'Add manual workflow refresh button', overlay: 'check-green' },
      { id: 't6', kind: 'Extension', label: 'Build per-project workflow rollouts', overlay: 'dot-blue' },
      { id: 't7', kind: 'Extension', label: 'Create webhook handler for workflows', overlay: 'pulse-amber' },
      { id: 't8', kind: 'BugReport', label: 'Fix workflow file loader race', overlay: 'error-red' },
      { id: 't9', kind: 'Extension', label: 'Implement workflow validation', overlay: 'dot-purple' },
      { id: 't10', kind: 'Extension', label: 'Remove workflow create/update legacy', overlay: 'x-gray' },
      { id: 't11', kind: 'Extension', label: 'Update workflow settings UI', overlay: 'dot-blue' },
    ],
  },
  {
    id: 'g3', kind: 'folder', label: 'Ideas', expanded: true, folderStatus: 'dot-blue',
    children: [
      { id: 't13', kind: 'Extension', label: 'Feedback & Bug Report System', overlay: 'dot-purple' },
      { id: 't14', kind: 'LocalOffer', label: 'Idea Inbox — rapid feature capture', overlay: 'dot-purple' },
      { id: 't15', kind: 'Extension', label: 'Static Site Generation', overlay: 'dot-blue' },
      { id: 't16', kind: 'Extension', label: 'Wizard Framework & New Project flow', overlay: 'pulse-amber' },
    ],
  },
  {
    id: 'g4', kind: 'folder', label: 'Infrastructure', expanded: true, folderStatus: 'check-green',
    children: [
      {
        id: 'sg1', kind: 'folder', label: 'Activate Containerized Workflows',
        expanded: true, folderStatus: 'pulse-amber',
        children: [
          { id: 't18', kind: 'Extension', label: 'Add runs_on to a workflow', overlay: 'check-green' },
        ],
      },
    ],
  },
];

function TevTreeRow({ node, depth = 0 }) {
  const [expanded, setExpanded] = React.useState(node.expanded ?? false);
  const isFolder = node.kind === 'folder';
  const isLeaf = !node.children;

  return (
    <>
      <div
        className={`tev-row ${node.selected ? 'is-selected' : ''} ${isFolder ? 'is-folder' : ''}`}
        style={{ paddingLeft: 10 + depth * 22 }}
        onClick={() => !isLeaf && setExpanded((x) => !x)}
      >
        {!isLeaf ? (
          <span className={`tev-caret ${expanded ? 'is-open' : ''}`}>▸</span>
        ) : (
          <span className="tev-caret-spacer" />
        )}
        <span className="tev-icon">
          {isFolder
            ? <MIcon name="Folder" size={14} />
            : <MIcon name={node.kind} size={14} />}
          {node.overlay ? <StatusOverlay kind={node.overlay} /> : null}
          {isFolder && node.folderStatus ? <StatusOverlay kind={node.folderStatus} /> : null}
        </span>
        <span className="tev-row-label">{node.label}</span>
      </div>
      {!isLeaf && expanded && (
        <div className="tev-tree-children" style={{ '--tev-depth': depth }}>
          {node.children.map((c) => (
            <TevTreeRow key={c.id} node={c} depth={depth + 1} />
          ))}
        </div>
      )}
    </>
  );
}

function TaskEditView({ embedded = false, initialTab = 'content' }) {
  const [mode, setMode] = React.useState('edit');
  const [tab, setTab] = React.useState(initialTab);
  const [execOpen, setExecOpen] = React.useState(false);

  React.useEffect(() => {
    if (!execOpen) return;
    const onDoc = (e) => {
      if (!e.target.closest('.tev-exec-wrap')) setExecOpen(false);
    };
    document.addEventListener('click', onDoc);
    return () => document.removeEventListener('click', onDoc);
  }, [execOpen]);

  return (
    <div className={`tev ${embedded ? 'tev-embedded' : ''}`}>
      {!embedded && (
        <div className="tev-bar">
        <div className="tev-crumbs">
          <span className="tev-crumb">SourceWeaver</span>
          <span className="tev-crumb-sep">/</span>
          <span className="tev-crumb">SourceWeaver</span>
          <span className="tev-crumb-sep">/</span>
          <span className="tev-crumb">Component integration tests with real SignalR (3 of 3)</span>
          <span className="tev-crumb-sep">/</span>
          <span className="tev-crumb is-current">Implement MergeQueuePanel SignalR tests</span>
        </div>
          <div className="tev-bar-right">
            <div className="tev-progress"><span /></div>
            <div className="tev-bar-tabs">
              <button className="is-active">WORKSPACE</button>
              <button>WORKFLOWS</button>
              <button>MERGE QUEUE</button>
              <button>SETTINGS</button>
            </div>
          </div>
        </div>
      )}

      <div className="tev-body">
        <aside className="tev-side">
          <div className="tev-search">
            <span className="tev-search-icon">⌕</span>
            <input placeholder="Search workspace..." />
          </div>
          <div className="tev-side-controls">
            <div className="tev-filter-row">
              <button className="tev-filter is-active" title="Features">
                <MIcon name="Extension" size={13} />
              </button>
              <button className="tev-filter" title="Tasks">
                <MIcon name="LocalOffer" size={13} />
              </button>
              <button className="tev-filter" title="Bugs">
                <MIcon name="BugReport" size={13} />
              </button>
              <button className="tev-filter" title="Folders">
                <MIcon name="Folder" size={13} />
              </button>
              <button className="tev-filter" title="Docs">
                <MIcon name="Description" size={13} />
              </button>
            </div>
            <button className="tev-new">+ NEW</button>
          </div>
          <div className="tev-tree">
            {TEV_TREE.map((g) => <TevTreeRow key={g.id} node={g} />)}
          </div>
          <div className="tev-side-foot">
            <span>5 features · 1 bug · 13 tasks</span>
          </div>
        </aside>

        <main className="tev-main">
          <div className="tev-tabs-row">
            <div className="tev-tabs">
              <button
                className={tab === 'content' ? 'is-active' : ''}
                onClick={() => setTab('content')}
              >Content</button>
              <button
                className={tab === 'activity' ? 'is-active' : ''}
                onClick={() => setTab('activity')}
              >Activity</button>
            </div>
          </div>

          {tab === 'activity' ? (
            <div className="tev-activity">
              <PullRequestPanel />
              <WorkflowRunsPanel />
              <EventTimelinePanel tick={0} />
            </div>
          ) : (
          <React.Fragment>
          <div className="tev-titlebar">
            <div className="tev-titlebar-left">
              <span className="tev-task-icon">
                <MIcon name="Extension" size={14} />
                <StatusOverlay kind="pulse-amber" />
              </span>
              <span className="tev-task-name">Implement MergeQueuePanel SignalR tests</span>
            </div>
            <div className="tev-titlebar-right">
              <button className="tev-save tev-save-disabled">SAVE</button>
              <div className="tev-mode-tabs">
                <button
                  className={mode === 'edit' ? 'is-active' : ''}
                  onClick={() => setMode('edit')}
                >EDIT</button>
                <button
                  className={mode === 'split' ? 'is-active' : ''}
                  onClick={() => setMode('split')}
                >SPLIT</button>
                <button
                  className={mode === 'preview' ? 'is-active' : ''}
                  onClick={() => setMode('preview')}
                >PREVIEW</button>
              </div>
              <div className="tev-exec-wrap">
                <button className="tev-exec-play">
                  <span className="tev-exec-play-icon">▶</span>
                  <span>RUN</span>
                </button>
                <button
                  className="tev-exec-menu"
                  onClick={() => setExecOpen((x) => !x)}
                  aria-haspopup="true"
                  aria-expanded={execOpen}
                >
                  <span>Workspace Task Execution</span>
                  <span className="tev-exec-caret">▾</span>
                </button>
                {execOpen && (
                  <div className="tev-exec-pop" role="menu">
                    <div className="tev-exec-pop-head">Workflows</div>
                    <button className="tev-exec-pop-item is-selected" role="menuitem">
                      <span className="tev-exec-pop-dot" />
                      <span className="tev-exec-pop-name">Workspace Task Execution</span>
                      <span className="tev-exec-pop-meta">default</span>
                    </button>
                    <button className="tev-exec-pop-item" role="menuitem">
                      <span className="tev-exec-pop-dot" />
                      <span className="tev-exec-pop-name">Create/Update tickets</span>
                      <span className="tev-exec-pop-meta">v2.1</span>
                    </button>
                    <button className="tev-exec-pop-item" role="menuitem">
                      <span className="tev-exec-pop-dot" />
                      <span className="tev-exec-pop-name">Califry feature</span>
                      <span className="tev-exec-pop-meta">v0.7</span>
                    </button>
                    <button className="tev-exec-pop-item" role="menuitem">
                      <span className="tev-exec-pop-dot" />
                      <span className="tev-exec-pop-name">Hotfix triage</span>
                      <span className="tev-exec-pop-meta">v1.4</span>
                    </button>
                    <button className="tev-exec-pop-item" role="menuitem">
                      <span className="tev-exec-pop-dot" />
                      <span className="tev-exec-pop-name">Spike & report</span>
                      <span className="tev-exec-pop-meta">v0.3</span>
                    </button>
                    <div className="tev-exec-pop-foot">
                      <span>+ Add workflow…</span>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="tev-doc">
            <div className="tev-doc-edit">
              <div className="tev-doc-line"><span className="tev-md-h1"># Implement MergeQueuePanel SignalR tests</span></div>
              <div className="tev-doc-blank" />
              <div className="tev-doc-line"><span className="tev-md-h2">## Overview</span></div>
              <div className="tev-doc-blank" />
              <div className="tev-doc-line">
                Create a proof-of-concept test class demonstrating real SignalR testing by covering <code>MergeQueuePanel</code> component scenarios. This validates the complete testing chain: render component → trigger server state change → verify broadcast-driven re-render within timeout.
              </div>
              <div className="tev-doc-blank" />
              <div className="tev-doc-line"><span className="tev-md-h2">## Technical Decisions</span></div>
              <div className="tev-doc-blank" />
              <ul className="tev-doc-list">
                <li>Target <code>MergeQueuePanel</code> component (chosen due to history of hub-driven refresh bugs)</li>
                <li>Minimum 2 tests as specified</li>
                <li>Use seeded queue state for test setup</li>
                <li>Test state changes via endpoint triggers (enqueue/approve/retry operations)</li>
                <li>All assertions must use bounded timeout pattern</li>
              </ul>
              <div className="tev-doc-blank" />
              <div className="tev-doc-line"><span className="tev-md-h2">## Scope</span></div>
              <div className="tev-doc-blank" />
              <div className="tev-doc-line"><b>In scope:</b></div>
              <ul className="tev-doc-list">
                <li>New test class using <code>SignalRIntegrationComponentTestBase</code></li>
              </ul>
            </div>
          </div>

          <div className="tev-props">
            <div className="tev-props-tabs">
              <button className="is-active">▾ Properties</button>
              <span className="tev-props-spacer" />
              <button>▸ Links (2 depends on, 1 blocks)</button>
            </div>
            <div className="tev-props-grid">
              <label className="tev-field">
                <span className="tev-field-label">Status</span>
                <span className="tev-select">
                  <span>Open</span>
                  <span className="tev-select-caret">▾</span>
                </span>
              </label>
              <label className="tev-field">
                <span className="tev-field-label">Priority</span>
                <span className="tev-select">
                  <span>Medium</span>
                  <span className="tev-select-caret">▾</span>
                </span>
              </label>
              <label className="tev-field">
                <span className="tev-field-label">Tags</span>
                <span className="tev-select tev-select-empty">
                  <span>Add tag…</span>
                  <span className="tev-select-caret">▾</span>
                </span>
              </label>
            </div>
          </div>
          </React.Fragment>
          )}
        </main>
      </div>
    </div>
  );
}

Object.assign(window, { TaskEditView });
