function homeReviewDraft(openReqForm, prefill) {
  if (typeof openReqForm !== 'function') return false;
  openReqForm({ prefill });
  return true;
}

function HomeScreen() {
  const data = window.E8DATA || {};
  const persona = window.e8ActivePersona ? window.e8ActivePersona() : data.user || {};
  const personaName = persona.name || '';
  const firstName = personaName.split(' ')[0] || 'there';
  const workspace = window.E8Workspace;
  const preference = workspace && workspace.get ? workspace.get(personaName) : { home: {}, pinSets: [] };
  const onboarded = !!(preference.home && preference.home.onboardingComplete);
  const [prompt, setPrompt] = React.useState('');
  const [outcome, setOutcome] = React.useState(null);
  const [pendingPrompt, setPendingPrompt] = React.useState(null);
  const [showDisclosure, setShowDisclosure] = React.useState(false);
  const [tourOpen, setTourOpen] = React.useState(false);
  const [planner, setPlanner] = React.useState(() => window.E8HomePlanner ? window.E8HomePlanner.getState() : { status: 'idle' });
  const [, setVersion] = React.useState(0);
  const promptRef = React.useRef(null);

  React.useEffect(() => (
    window.E8HomePlanner ? window.E8HomePlanner.subscribe(setPlanner) : undefined
  ), []);
  React.useEffect(() => () => {
    if (window.E8HomePlanner) window.E8HomePlanner.cancel();
  }, []);
  React.useEffect(() => (
    window.E8Events ? window.E8Events.subscribe(['workspace:changed', 'store:changed', 'persona:changed', 'comms:changed'], () => setVersion((version) => version + 1)) : undefined
  ), []);
  React.useEffect(() => {
    const focusCommand = () => {
      if (window.__e8HomePrompt) {
        setPrompt(String(window.__e8HomePrompt));
        delete window.__e8HomePrompt;
      }
      window.requestAnimationFrame(() => promptRef.current && promptRef.current.focus());
    };
    window.addEventListener('e8-focus-home-command', focusCommand);
    if (window.__e8HomePrompt) focusCommand();
    return () => window.removeEventListener('e8-focus-home-command', focusCommand);
  }, []);

  const model = window.E8HomeData
    ? window.E8HomeData.build(data, persona, workspace)
    : { profile: { chips: [], firstRun: { cards: [] } }, focus: [], health: [], continueItems: [] };
  const profile = model.profile || {};
  const role = persona.role || 'recruiter';
  const navIds = workspace && workspace.defaultNavOrder ? workspace.defaultNavOrder : [];
  const metrics = window.E8HomeMetrics;
  const track = (event, target, source) => {
    if (metrics) metrics.track(event, { role, target, source: source || 'home' });
  };
  React.useEffect(() => {
    if (metrics) metrics.track('home_view', { role, target: 'home', source: 'home' });
  }, [metrics, role]);

  const markOnboarded = () => {
    if (workspace && workspace.setHomeOnboardingComplete) workspace.setHomeOnboardingComplete(personaName, true);
  };
  const go = (path, event, target) => {
    if (event) track(event, target || path);
    navigate(path);
  };
  const navigateAction = (action) => {
    if (!action || (action.type !== 'navigate' && action.type !== 'search')) return false;
    track('command_outcome', action.type === 'search' ? action.recordType : action.path, action.type);
    navigate(action.path);
    markOnboarded();
    return true;
  };
  const useOutcome = (next) => {
    if (!next) return;
    if (next.kind === 'action' && navigateAction(next.action)) {
      setOutcome(null);
      return;
    }
    track('command_outcome', next.kind || 'unknown', next.source || 'planner');
    setOutcome(next);
  };
  const runPlan = (nextPrompt) => {
    if (!window.E8HomePlanner) return;
    track('command_submit', 'command');
    window.E8HomePlanner.plan({ personaName, prompt: nextPrompt, data, navIds })
      .then(useOutcome)
      .catch((error) => {
        if (!error || error.name !== 'AbortError') setOutcome({ kind: 'unsupported', message: 'The assistant is unavailable right now. Try a prompt chip or navigate directly.' });
      });
  };
  const submitPrompt = (value) => {
    if (!value || !window.E8HomePlanner) return;
    const consent = preference.home ? preference.home.modelConsent : null;
    if (consent === null) {
      window.E8HomePlanner.checkSupport().then((supported) => {
        if (supported) {
          setPendingPrompt(value);
          setShowDisclosure(true);
        } else {
          runPlan(value);
        }
      }).catch(() => runPlan(value));
      return;
    }
    runPlan(value);
  };
  const submit = (event) => {
    event.preventDefault();
    submitPrompt(prompt.trim());
  };
  const chooseConsent = (value) => {
    if (!window.E8HomePlanner || !pendingPrompt) return;
    window.E8HomePlanner.setConsent(personaName, value);
    const valueToPlan = pendingPrompt;
    setPendingPrompt(null);
    setShowDisclosure(false);
    runPlan(valueToPlan);
  };
  const runChip = (chip) => {
    const value = chip.prompt || chip.label;
    setPrompt(value);
    track('prompt_chip_click', chip.label);
    submitPrompt(value);
  };
  const resolveChoice = (choice) => {
    if (!outcome || !outcome.plan || !window.E8HomeIntents) return;
    const key = outcome.plan.intent === 'navigate' ? 'destination' : 'id';
    const plan = { ...outcome.plan, entities: { ...outcome.plan.entities, [key]: choice.id } };
    useOutcome(window.E8HomeIntents.planToOutcome(plan, data, navIds));
  };
  const reviewDraft = (prefill) => {
    homeReviewDraft(window.e8OpenReqForm, prefill);
    track('command_outcome', 'job_draft_review', 'review');
    markOnboarded();
  };
  const runSetupCard = (card) => {
    track('setup_complete', card.action || card.route || card.workspaceTab || 'setup');
    markOnboarded();
    if (card.action === 'tour') {
      setTourOpen(!tourOpen);
      return;
    }
    if (card.workspaceTab) {
      window.dispatchEvent(new CustomEvent('e8-open-workspace', { detail: { tab: card.workspaceTab } }));
      return;
    }
    if (card.route) navigate(card.route);
  };
  const plannerBusy = ['checking', 'loading', 'planning'].includes(planner.status);
  const displaySetName = (name) => name === 'My desk' ? 'Saved work' : (name || 'Saved work');

  return (
    <div className="e8-content">
      <div className="e8-page e8-home">
        <header className="e8-home-hero">
          <div className="e8-home-greeting-row">
            <p className="e8-home-greet">Good morning, {firstName}</p>
            <span className="e8-home-role">{profile.label || persona.label || 'Your workspace'}</span>
          </div>
          <h1 className="e8-h1">What do you want to move forward?</h1>
        </header>

        <form className="e8-home-canvas" id="e8-home-command" onSubmit={submit}>
          <span className="e8-home-spark" aria-hidden="true">✦</span>
          <label className="e8-sr-only" htmlFor="e8-home-prompt">Ask ELEV8</label>
          <input
            ref={promptRef}
            id="e8-home-prompt"
            value={prompt}
            onChange={(event) => setPrompt(event.target.value)}
            placeholder={profile.placeholder || 'Find a record or move work forward…'}
            disabled={plannerBusy}
          />
          <button className="e8-home-go" type="submit" aria-label="Continue" disabled={plannerBusy || !prompt.trim()}>
            <span className="material-symbols-outlined" aria-hidden="true">arrow_forward</span>
          </button>
        </form>
        <p className="e8-home-safeguard"><span className="material-symbols-outlined" aria-hidden="true">verified_user</span>Search and navigation happen right away. You'll review drafts and changes before they run.</p>

        <div className="e8-home-chips" aria-label="Suggested prompts">
          {(profile.chips || []).map((chip) => (
            <button key={chip.label} type="button" className={`e8-home-chip ${chip.tone || 'sage'}`} onClick={() => runChip(chip)}>
              <span className="material-symbols-outlined" aria-hidden="true">{chip.icon || 'arrow_forward'}</span>
              {chip.label}
            </button>
          ))}
        </div>

        {showDisclosure ? (
          <section className="e8-home-panel" aria-live="polite">
            <h2>Use the on-device assistant?</h2>
            <p>A one-time model download stays cached on this device. Your prompts and workspace data are not sent to an inference service.</p>
            <div className="e8-home-actions">
              <button type="button" className="e8-home-btn primary" onClick={() => chooseConsent(true)}>Enable on-device assistant</button>
              <button type="button" className="e8-home-btn" onClick={() => chooseConsent(false)}>Use quick commands only</button>
            </div>
          </section>
        ) : null}

        {plannerBusy ? (
          <section className="e8-home-panel" aria-live="polite">
            <p>{planner.detail || 'Preparing your request.'}{planner.progress ? ` · ${Math.round(planner.progress * 100)}%` : ''}</p>
            <div className="e8-home-actions">
              <button type="button" className="e8-home-btn" onClick={() => window.E8HomePlanner && window.E8HomePlanner.cancel()}>Cancel</button>
            </div>
          </section>
        ) : null}

        {outcome && outcome.kind === 'action' && outcome.action && outcome.action.type === 'open_job_draft' ? (
          <section className="e8-home-panel e8-home-review-panel">
            <span className="e8-home-panel-kicker">Draft ready for review</span>
            <h2>{outcome.action.prefill.job.title || 'Untitled job'}</h2>
            <p>{outcome.action.prefill.job.client || 'Client to confirm'} · {outcome.action.prefill.job.location || 'Location to confirm'}</p>
            <div className="e8-home-actions">
              <button type="button" className="e8-home-btn primary" onClick={() => reviewDraft(outcome.action.prefill)}>Review job draft</button>
            </div>
          </section>
        ) : null}

        {outcome && outcome.kind === 'action' && outcome.action && outcome.action.type === 'review_plan' ? (
          <section className="e8-home-panel e8-home-review-panel">
            <span className="e8-home-panel-kicker">Proposed workflow</span>
            <h2>{outcome.action.title}</h2>
            <p>{outcome.action.summary}</p>
            <ol>{(outcome.action.steps || []).map((step) => <li key={step}>{step}</li>)}</ol>
            <div className="e8-home-actions">
              <button type="button" className="e8-home-btn primary" onClick={() => go(outcome.action.path, 'command_outcome', 'review_plan')}>{outcome.action.actionLabel || 'Review sources'}</button>
              <button type="button" className="e8-home-btn" onClick={() => setOutcome(null)}>Dismiss</button>
            </div>
          </section>
        ) : null}

        {outcome && outcome.kind === 'clarification' ? (
          <section className="e8-home-panel" aria-live="polite">
            <p>{outcome.message}</p>
            <div className="e8-home-actions wrap">
              {(outcome.choices || []).map((choice) => (
                <button key={choice.id} type="button" className="e8-home-btn" onClick={() => resolveChoice(choice)}>{choice.label}</button>
              ))}
            </div>
          </section>
        ) : null}

        {outcome && outcome.kind === 'unsupported' ? (
          <p className="e8-home-note e8-home-command-note" aria-live="polite">{outcome.message}</p>
        ) : null}

        {!onboarded ? (
          <section className="e8-home-section e8-home-onboarding">
            <div className="e8-home-section-head">
              <div>
                <span className="e8-home-eyebrow">A two-minute start</span>
                <h2>{profile.firstRun && profile.firstRun.title}</h2>
                <p>{profile.firstRun && profile.firstRun.description}</p>
              </div>
              <button type="button" className="e8-home-text-btn" onClick={() => { markOnboarded(); track('setup_complete', 'skip'); }}>Skip for now</button>
            </div>
            <div className="e8-home-setup">
              {((profile.firstRun && profile.firstRun.cards) || []).map((card) => (
                <button key={card.title} type="button" className="e8-home-setup-card" onClick={() => runSetupCard(card)}>
                  <span className="e8-home-card-title">{card.title}</span>
                  <span className="e8-home-card-why">{card.why}</span>
                  <span className="e8-home-card-action"><span>{card.actionLabel}</span><span aria-hidden="true">→</span></span>
                </button>
              ))}
            </div>
            {tourOpen ? <p className="e8-home-tour-note">ELEV8 keeps familiar records and permissions underneath the command layer: start from work, review the system’s proposal, then confirm consequential changes.</p> : null}
          </section>
        ) : null}

        <section className="e8-home-changes" aria-label="Changes since your last visit">
          <span className="material-symbols-outlined" aria-hidden="true">auto_awesome</span>
          <span><b>Since your last visit</b>{model.changes}</span>
          <button type="button" onClick={() => go('today', 'work_queue_click', 'changes')}>Review changes <span aria-hidden="true">→</span></button>
        </section>

        <section className="e8-home-section">
          <div className="e8-home-section-head e8-home-priority-head">
            <div>
              <span className="e8-home-eyebrow">Prioritized from live work</span>
              <h2>Up next</h2>
            </div>
            <div className="e8-home-focus-controls">
              {preference.pinSets && preference.pinSets.length ? (
                <label className="e8-home-focus-set">
                  <span>Focus set</span>
                  <select
                    value={preference.activePinSetId}
                    onChange={(event) => {
                      workspace.activatePinSet(personaName, event.target.value);
                      track('focus_set_change', event.target.value);
                    }}
                  >
                    {preference.pinSets.map((set) => <option key={set.id} value={set.id}>{displaySetName(set.name)}</option>)}
                  </select>
                </label>
              ) : null}
              <button type="button" className="e8-home-text-btn" onClick={() => go('today', 'work_queue_click', 'up_next')}>View work queue</button>
            </div>
          </div>
          <div className="e8-home-focus">
            <div className="e8-home-priority-grid">
              {model.focus.length ? model.focus.map((card, index) => (
                <button key={card.id} type="button" className={`e8-home-card ${card.tone || 'neutral'}`} onClick={() => go(card.route, 'priority_click', card.id)}>
                  <span className="e8-home-priority-number">{String(index + 1).padStart(2, '0')}</span>
                  <span className="e8-home-card-main">
                    <span className="e8-home-card-icon material-symbols-outlined" aria-hidden="true">{card.icon || 'task_alt'}</span>
                    <span className="e8-home-card-copy">
                      <span className="e8-home-card-title">{card.title}</span>
                      <span className="e8-home-card-why">{card.why}</span>
                    </span>
                  </span>
                  <span className="e8-home-card-action"><span>{card.actionLabel}</span><span aria-hidden="true">→</span></span>
                </button>
              )) : <div className="e8-home-empty"><span className="material-symbols-outlined">task_alt</span><b>Nothing urgent</b><p>Your full work queue is still available when you are ready.</p></div>}
            </div>
            <aside className="e8-home-pulse" aria-label={profile.healthTitle || 'Workspace health'}>
              <span className="e8-home-eyebrow">Live workspace data</span>
              <h3>{profile.healthTitle || 'Workspace health'}</h3>
              <div className="e8-home-health-list">
                {(model.health || []).map((metric) => (
                  <button key={metric.id} type="button" className={metric.tone === 'warning' ? 'warn' : ''} onClick={() => go(metric.route, 'health_click', metric.id)}>
                    <span className="material-symbols-outlined" aria-hidden="true">{metric.icon}</span>
                    <span><b>{metric.value}</b><small>{metric.label}</small></span>
                    <span className="material-symbols-outlined e8-home-health-arrow" aria-hidden="true">chevron_right</span>
                  </button>
                ))}
              </div>
              <p>Counts update from the records and queues you can access.</p>
            </aside>
          </div>
        </section>

        <section className="e8-home-section e8-home-continue-section">
          <div className="e8-home-section-head">
            <div>
              <span className="e8-home-eyebrow">Saved and recent</span>
              <h2>Continue working</h2>
            </div>
            <button type="button" className="e8-home-text-btn" onClick={() => window.dispatchEvent(new CustomEvent('e8-open-workspace', { detail: { tab: 'focus' } }))}>Manage saved work</button>
          </div>
          {model.continueItems && model.continueItems.length ? (
            <div className="e8-home-recents">
              {model.continueItems.map((record) => (
                <button key={`${record.type}:${record.id}`} type="button" onClick={() => go(record.route, 'continue_click', `${record.type}:${record.id}`)}>
                  <span className="e8-home-recent-icon material-symbols-outlined" aria-hidden="true">{record.type === 'job' ? 'work' : record.type === 'candidate' ? 'person' : record.type === 'contact' ? 'contacts' : 'history'}</span>
                  <span className="e8-home-recent-copy"><b>{record.label}</b><small>{record.context === 'My desk' ? 'Saved work' : record.context}{record.sub ? ` · ${record.sub}` : ''}</small></span>
                  {record.saved ? <span className="e8-home-saved-badge">Saved</span> : null}
                  <span className="material-symbols-outlined" aria-hidden="true">chevron_right</span>
                </button>
              ))}
            </div>
          ) : (
            <div className="e8-home-empty e8-home-empty-inline">
              <span className="material-symbols-outlined">bookmark_add</span>
              <span><b>Save work to make Home yours</b><p>Open a job, person, account, or task and use Save. Recent records will appear here automatically.</p></span>
            </div>
          )}
        </section>
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, homeReviewDraft });
