// AppShell.jsx — full product mock of the SourceWeaver app,
// rendered in the green/black/white palette.

function AppShellMock({ initialTab = 'workspace', initialSubTab = 'content' }) {
  // Animate the "Broken" head item walking through merge-queue states,
  // matching the real product's lifecycle: Queued → Syncing → Rebasing → Testing → Broken.
  const [tick, setTick] = React.useState(0);
  const [activeTab, setActiveTab] = React.useState(initialTab);
  React.useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 2400);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="appshell">
      <div className="preview-ribbon" aria-label="Design preview"><span>preview</span></div>
      <AppTopBar activeTab={activeTab} onTabChange={setActiveTab} />
      <div className="appshell-body">
        {activeTab === 'workspace' ? (
          <TaskEditView embedded initialTab={initialSubTab} />
        ) : (
          <React.Fragment>
            <AppSidebar />
            <AppContent tick={tick} activeTab={activeTab} />
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

function AppTopBar({ activeTab, onTabChange }) {
  const tabs = [
    { id: 'workspace',  label: 'WORKSPACE'   },
    { id: 'workflows',  label: 'WORKFLOWS'   },
    { id: 'mergequeue', label: 'MERGE QUEUE' },
    { id: 'settings',   label: 'SETTINGS'    },
  ];
  return (
    <div className="apptop">
      <div className="apptop-left">
        <span className="apptop-brand">
          <span className="apptop-brand-mark">S</span>
          <span>sourceweaver</span>
        </span>
        <span className="apptop-sep">/</span>
        <span className="apptop-crumb">Auth &amp; SSO</span>
        <span className="apptop-sep">/</span>
        <span className="apptop-crumb apptop-crumb-current">
          OAuth fallback for self-hosted SSO <span className="apptop-counter">3 of 5</span>
        </span>
      </div>
      <div className="apptop-right">
        <div className="apptop-progress">
          <div className="apptop-progress-fill" />
        </div>
        <div className="apptop-tabs">
          {tabs.map(t => (
            <button
              key={t.id}
              type="button"
              className={`apptop-tab ${activeTab === t.id ? 'is-active' : ''}`}
              onClick={() => onTabChange(t.id)}
            >{t.label}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

function AppSidebar() {
  const tree = [
    { kind: 'folder-open', id: 'FLDR-100', title: 'Auth & SSO', open: true },
    { kind: 'Extension', id: 'FEAT-001', title: 'OAuth fallback for self-hosted SSO',  overlay: 'pulse-amber', child: 1, active: true, questions: 2 },
    { kind: 'LocalOffer',id: 'TASK-002', title: 'Add provider config schema',           overlay: 'check-green', child: 2 },
    { kind: 'LocalOffer',id: 'TASK-003', title: 'Implement token exchange',             overlay: 'dot-blue',    child: 2 },
    { kind: 'BugReport', id: 'BUG-004',  title: 'Refresh-token loop on 401',            overlay: 'pulse-amber', child: 2 },
    { kind: 'folder',    id: 'FLDR-200', title: 'Git-based workflows', open: true },
    { kind: 'Extension', id: 'FEAT-005', title: 'Multi-repo workspace switcher',        overlay: 'dot-purple',  child: 1 },
    { kind: 'LocalOffer',id: 'TASK-006', title: 'Build per-project workflow registry',  overlay: 'check-green', child: 1 },
    { kind: 'LocalOffer',id: 'TASK-007', title: 'Implement workflow file loader',       overlay: 'dot-blue',    child: 1 },
    { kind: 'BugReport', id: 'BUG-008',  title: 'SignalR reconnect storm under load',   overlay: 'error-red',   child: 1 },
    { kind: 'folder',    id: 'FLDR-300', title: 'Infrastructure', open: false },
  ];

  return (
    <aside className="appside">
      <div className="appside-search">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 1 0-.7.7l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/></svg>
        <span>Search workspace…</span>
      </div>
      <div className="appside-chips">
        <ChipIcon name="Extension" />
        <ChipIcon name="Folder" />
        <ChipIcon name="LocalOffer" />
        <ChipIcon name="BugReport" />
        <ChipIcon name="Cancel" muted />
        <span className="appside-chip-spacer" />
        <button className="appside-newbtn">
          <span>+</span> NEW
        </button>
      </div>
      <div className="appside-tree">
        {tree.map((r, i) => {
          if (r.kind === 'folder' || r.kind === 'folder-open') {
            return (
              <div key={i} className="appside-folder">
                <span className="appside-folder-caret">{r.kind === 'folder-open' ? '▾' : '▸'}</span>
                <MIcon name="Folder" size={16} />
                <span className="appside-folder-name">{r.title}</span>
              </div>
            );
          }
          return (
            <div key={i} className={`appside-row appside-child-${r.child} ${r.active ? 'is-active' : ''}`}>
              <span className="appside-icon">
                <MIcon name={r.kind} size={16} />
                <StatusOverlay kind={r.overlay} />
                {r.questions ? <span className="appside-q">{r.questions}</span> : null}
              </span>
              <span className="appside-row-title">{r.title}</span>
            </div>
          );
        })}
      </div>
    </aside>
  );
}

function ChipIcon({ name, muted }) {
  return (
    <span className={`appside-chip ${muted ? 'is-muted' : ''}`}>
      <MIcon name={name} size={14} />
    </span>
  );
}

function AppContent({ tick, activeTab }) {
  return (
    <div className="appmain">
      <div className="appmain-scroll">
        {activeTab === 'workflows' && (
          <React.Fragment>
            <PullRequestPanel />
            <WorkflowRunsPanel />
          </React.Fragment>
        )}
        {activeTab === 'mergequeue' && (
          <React.Fragment>
            <MergeQueuePanel tick={tick} />
            <EventTimelinePanel tick={tick} />
          </React.Fragment>
        )}
        {activeTab === 'settings' && (
          <section className="appsec">
            <div className="appsec-h">Settings</div>
            <div className="appsec-pr" style={{ color: 'var(--ink-3)', fontSize: 12, padding: '20px 16px' }}>
              Project settings, secrets, and integrations live here. Coming soon in this prototype.
            </div>
          </section>
        )}
      </div>
    </div>
  );
}

function PullRequestPanel() {
  return (
    <section className="appsec">
      <div className="appsec-h">Pull Request</div>
      <div className="appsec-pr">
        <div className="appsec-pr-row">
          <span className="appsec-pr-label">source</span>
          <a className="appsec-pr-link">#1142 oauth-fallback-self-hosted-sso-001a</a>
        </div>
        <div className="appsec-pr-row">
          <span className="appsec-pr-label">target</span>
          <a className="appsec-pr-link appsec-pr-link-target">work-item/auth-sso/oauth-fallback-3-of-5</a>
          <span className="appsec-pill appsec-pill-open">Open</span>
        </div>
        <div className="appsec-pr-foot">
          <span>Opened by sourceweaver-bot</span>
          <span className="appsec-pr-time">12h ago</span>
        </div>
      </div>
    </section>
  );
}

function MergeQueuePanel({ tick }) {
  // Cycle status pill across realistic states
  const cycle = [
    { label: 'Broken',     tone: 'broken' },
    { label: 'Rebasing',   tone: 'progress' },
    { label: 'Testing',    tone: 'progress' },
    { label: 'Broken',     tone: 'broken' },
  ];
  const status = cycle[tick % cycle.length];

  return (
    <section className="appsec">
      <div className="appsec-h">Merge Queue</div>
      <div className="appsec-mq">
        <div className="appsec-mq-row">
          <span className="appsec-mq-label">
            <MIcon name="MergeType" size={14} color="var(--accent)" />
            Status:
          </span>
          <span className="appsec-mq-val">{status.label}</span>
          <span className={`appsec-pill appsec-pill-${status.tone}`}>{status.label}</span>
          <span className="appsec-mq-spacer" />
          <button className="appsec-eject">EJECT</button>
        </div>
        <div className="appsec-mq-meta">
          Position 5 in queue · Priority 0 · work-item/oauth-fallback-self-hosted-sso-001a · PR #1142 · Added 10h ago
        </div>
        <div className="appsec-mq-tags">
          <span className="appsec-mq-retry">2 retries</span>
        </div>
        <div className="appsec-mq-fail">
          <span className="appsec-mq-fail-dot" />
          CI checks failure · workflow <code>merge-queue-fix.yaml</code> dispatched
        </div>
      </div>
    </section>
  );
}

function EventTimelinePanel({ tick }) {
  // Flowing timeline of state transitions, latest at top.
  const events = [
    { from: 'Testing',  to: 'Broken',   tone: 'broken',   ago: '6h ago',  dur: '7m 4s' },
    { from: 'Rebasing', to: 'Testing',  tone: 'idle',     ago: '7h ago',  dur: '0s' },
    { from: 'Syncing',  to: 'Rebasing', tone: 'progress', ago: '7h ago',  dur: '0s' },
    { from: 'Queued',   to: 'Syncing',  tone: 'idle',     ago: '7h ago',  dur: '3h 23m' },
    { from: '—',        to: 'Queued',   tone: 'idle',     ago: '10h ago', dur: '—' },
  ];
  // Animate the head dot pulsing
  const liveIdx = tick % 2 === 0 ? 0 : -1;

  return (
    <section className="appsec">
      <div className="appsec-h">Event Timeline</div>
      <div className="apptl">
        {events.map((e, i) => (
          <div key={i} className={`apptl-row apptl-${e.tone} ${i === liveIdx ? 'is-live' : ''}`}>
            <span className="apptl-dot" />
            <div className="apptl-body">
              <div className="apptl-title">
                <span className="apptl-ago">{e.ago}</span>
                <span className="apptl-state-from">{e.from}</span>
                <span className="apptl-arrow">→</span>
                <span className="apptl-state-to">{e.to}</span>
              </div>
              <div className="apptl-meta">Duration: {e.dur}</div>
              <a className="apptl-link">View workflow run</a>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function WorkflowRunsPanel() {
  const runs = [
    { name: 'Workspace Task Execution', status: 'Running',       tone: 'progress', started: '5h ago',  dur: '5h 39m', expanded: true },
    { name: 'Workspace Task Execution', status: 'FailedRetried', tone: 'warn',     started: '6h ago',  dur: '44m 5s' },
    { name: 'merge-queue-fix',          status: 'Queued',        tone: 'queued',   started: '6h ago',  dur: '6h 53m' },
    { name: 'Workspace Task Execution', status: 'FailedRetried', tone: 'warn',     started: '7h ago',  dur: '16m 31s' },
    { name: 'merge-queue-fix',          status: 'Queued',        tone: 'queued',   started: '10h ago', dur: '10h 24m' },
    { name: 'PR Review',                status: 'Completed',     tone: 'done',     started: '10h ago', dur: '2m 52s' },
    { name: 'Workspace Task Execution', status: 'Completed',     tone: 'done',     started: '10h ago', dur: '18m 36s' },
  ];

  return (
    <section className="appsec">
      <div className="appsec-h">Workflow Runs</div>
      <div className="appwf">
        <div className="appwf-row appwf-head">
          <span>Workflow</span>
          <span>Status</span>
          <span>Started</span>
          <span>Duration</span>
        </div>
        {runs.map((r, i) => (
          <React.Fragment key={i}>
            <div className={`appwf-row ${r.expanded ? 'is-expanded' : ''}`}>
              <span className="appwf-name">
                <span className="appwf-caret">{r.expanded ? '▾' : '▸'}</span>
                {r.name}
              </span>
              <span><span className={`appsec-pill appsec-pill-${r.tone}`}>{r.status}</span></span>
              <span className="appwf-time">{r.started}</span>
              <span className="appwf-time">{r.dur}</span>
            </div>
            {r.expanded ? (
              <div className="appwf-expanded">
                <BranchingPipeline />
              </div>
            ) : null}
          </React.Fragment>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { AppShellMock });
