// views_automation.jsx — production Automation Designer, backed by /api/v1/automation.
(function () {
  const { useEffect, useMemo, useState } = React;

  const STAGES = [
    {
      id: 'audit', num: '01', title: 'Audit', img: 'assets/step-audit.png', accent: 'var(--emerald)',
      desc: 'See how AI engines read your brand today.',
      blurb: 'We connect your evidence, crawl the site, and score how generative engines currently see your brand. This is the source-of-truth baseline. Every number shows its working.'
    },
    {
      id: 'generate', num: '02', title: 'Generate', img: 'assets/step-generate.png', accent: 'var(--lime)',
      desc: 'AI drafts what engines need to cite you.',
      blurb: 'JiffyScore drafts the schema, briefs and answer-ready content that make you quotable. Drafts only: nothing touches your site until you approve it in the next step.'
    },
    {
      id: 'approve', num: '03', title: 'Approve', img: 'assets/step-approve.png', accent: 'var(--amber)',
      desc: 'Nothing ships without your yes.',
      blurb: 'The flow pauses here, on purpose. Review every change as a dry-run diff, approve asset by asset, and only then does anything move downstream.'
    },
    {
      id: 'publish', num: '04', title: 'Publish', img: 'assets/step-publish.png', accent: 'var(--coral)',
      desc: 'Ship approved changes to your stack.',
      blurb: 'Once you approve, JiffyScore pushes only approved assets to the destinations you connect: CMS, static export, or a downloadable pack. Live writes always need an explicit confirm.'
    },
    {
      id: 'monitor', num: '05', title: 'Monitor', img: 'assets/step-monitor.png', accent: 'var(--gold)',
      desc: 'Watch the score, catch every change.',
      blurb: 'Publishing is an action; monitoring is the loop. JiffyScore keeps watch, reruns what it should, and proves the published changes actually landed and moved the score.'
    }
  ];

  const STATUS = {
    done: { label: 'Complete', pill: 'pill--green', icon: 'check' },
    active: { label: 'In progress', pill: 'pill--lime', icon: 'refresh' },
    approval: { label: 'Needs your approval', pill: 'pill--amber', icon: 'alert' },
    waiting: { label: 'Waiting on approval', pill: 'pill--coral', icon: 'pause' },
    locked: { label: 'Waiting on publish', pill: 'pill--coral', icon: 'shield' },
    failed: { label: 'Failed', pill: 'pill--coral', icon: 'alert' }
  };

  const CTX = {
    client: ['Costa Verde Realty', 'Dunas Group', 'Atlantico Homes'],
    website: ['costaverde.es', 'dunasgroup.com', 'atlantico.es'],
    audit: ['Audit · 17 Jun 2026', 'Audit · 03 Jun 2026', 'Audit · 21 May 2026'],
    recipe: ['No recipe', 'Local SEO refresh', 'GEO answer-readiness', 'Citation recovery'],
    plan: ['Growth', 'Enterprise']
  };

  const EMPTY_REGISTRY = { modules: [], counts: null, countsByStep: {}, publishTargets: [] };

  function slug(value) {
    return String(value || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') || 'local';
  }

  function defaultContext(role, audit) {
    const workspaceMode = role === 'agency' ? 'agency' : 'client';
    const websiteUrl = audit?.websiteUrl || audit?.request?.websiteUrl || 'https://costaverde.es';
    const auditId = audit?.id || slug(CTX.audit[0]);
    return {
      workspaceMode,
      clientId: workspaceMode === 'agency' ? slug(CTX.client[0]) : 'self',
      websiteId: slug(websiteUrl.replace(/^https?:\/\//, '')),
      websiteUrl,
      auditId,
      recipeId: null,
      planKey: workspaceMode === 'agency' ? 'agency' : 'growth'
    };
  }

  function moduleMeta(registry, moduleKey) {
    return (registry?.modules || []).find((item) => item.moduleKey === moduleKey) || {};
  }

  function normalizeRegistry(input) {
    return {
      modules: Array.isArray(input?.modules) ? input.modules : [],
      counts: input?.counts || null,
      countsByStep: input?.countsByStep && typeof input.countsByStep === 'object' ? input.countsByStep : {},
      publishTargets: Array.isArray(input?.publishTargets) ? input.publishTargets : []
    };
  }

  function automationApi() {
    return window.JS_API?.automation || null;
  }

  function countLabel(counts) {
    return counts?.label || 'No modules available';
  }

  function stageStatus(run, stageId) {
    return run?.stepStates?.[stageId] || (stageId === 'audit' ? 'active' : 'locked');
  }

  function connectorState(run, index) {
    const left = stageStatus(run, STAGES[index].id);
    const right = stageStatus(run, STAGES[index + 1].id);
    if (left === 'done') return 'done';
    if (left === 'active' || right === 'active') return 'active';
    if (right === 'waiting' || right === 'approval') return 'paused';
    return 'idle';
  }

  function stateChip(state) {
    if (state === 'requires_setup') return { cls: 'tag--setup', icon: 'puzzle', text: 'Needs setup' };
    if (state === 'requires_upgrade') return { cls: 'tag--upgrade', icon: 'rocket', text: 'Upgrade' };
    if (state === 'agency_only') return { cls: 'tag--agency-lock', icon: 'shield', text: 'Agency only' };
    if (state === 'failed') return { cls: 'tag--agency-lock', icon: 'alert', text: 'Failed' };
    if (state === 'complete') return { cls: 'tag--agency', icon: 'check', text: 'Complete' };
    return null;
  }

  function targetClass(status) {
    if (status === 'Ready') return 'is-ready';
    if (status === 'Upgrade') return 'is-upgrade';
    return 'is-setup';
  }

  function AutomationView({ role, audit }) {
    const [ctx, setCtx] = useState(() => defaultContext(role, audit));
    const [run, setRun] = useState(null);
    const [registry, setRegistry] = useState(null);
    const [focus, setFocus] = useState('monitor');
    const [busy, setBusy] = useState('');
    const [error, setError] = useState('');

    useEffect(() => {
      setCtx(defaultContext(role, audit));
    }, [role, audit?.id]);

    useEffect(() => {
      let cancelled = false;
      (async () => {
        try {
          const api = automationApi();
          if (!api?.registry) throw new Error('Automation API client is not loaded. Refresh the page and sign in again.');
          const result = await api.registry(ctx);
          if (!cancelled) setRegistry(normalizeRegistry(result));
        } catch (e) {
          if (!cancelled) setError(e.message || String(e));
        }
      })();
      return () => { cancelled = true; };
    }, [ctx.workspaceMode, ctx.planKey]);

    async function act(label, fn) {
      setBusy(label);
      setError('');
      try {
        if (!automationApi()) throw new Error('Automation API client is not loaded. Refresh the page and sign in again.');
        const result = await fn();
        if (result?.run) setRun(result.run);
        return result;
      } catch (e) {
        setError(e.message || String(e));
        return null;
      } finally {
        setBusy('');
      }
    }

    async function createRun() {
      const result = await act('create', () => automationApi().createRun(ctx));
      if (result?.run) setFocus('audit');
    }

    async function refresh() {
      if (!run?.id) return;
      await act('refresh', () => automationApi().getRun(run.id));
    }

    async function toggleItem(item) {
      if (!run?.id) return;
      await act(item.moduleKey, () => automationApi().updateItem(run.id, item.moduleKey, !item.selected));
    }

    async function startStep(step) {
      if (!run?.id) return;
      await act(`start-${step}`, () => automationApi().startStep(run.id, step));
    }

    async function approveAll() {
      const pending = (run?.generatedAssets || []).filter((asset) => asset.status !== 'approved');
      let latest = run;
      for (const asset of pending) {
        const result = await automationApi().approve(run.id, { assetId: asset.id, decision: 'approved', reviewNote: 'Approved in local automation workflow.' });
        latest = result.run;
        setRun(latest);
      }
      return { run: latest };
    }

    const safeRegistry = normalizeRegistry(registry || EMPTY_REGISTRY);
    const displayCounts = run?.counts || safeRegistry.counts;
    const displayCountsByStep = run?.countsByStep || safeRegistry.countsByStep || {};
    const stage = STAGES.find((item) => item.id === focus) || STAGES[0];
    const items = (run?.items || []).filter((item) => item.step === stage.id);
    const canPublish = Boolean(run?.approvalSummary?.complete);
    const canMonitor = Boolean(run?.publishSummary?.complete || run?.publishSummary?.dryRunAccepted);
    const status = STATUS[stageStatus(run, stage.id)] || STATUS.locked;

    const ctxScope = ctx.workspaceMode === 'agency'
      ? `Running for ${CTX.client[0]} · ${ctx.websiteId} · ${ctx.auditId} · every run tagged clientId · websiteId · auditId`
      : `Scoped to your workspace · ${ctx.websiteId} · ${ctx.auditId || 'new audit'} · ${ctx.planKey} plan · every run tagged websiteId · auditId`;

    return (
      <div className="js-view js-view--wide automation-prototype">
        <main className="auto-main">
          <div className="auto-wrap">
            <header className="auto-head">
              <span className="je-eyebrow">JIFFYSCORE AUTOMATION · END TO END</span>
              <h1>Your visibility, <em>on autopilot.</em></h1>
              <p className="lead">Five steps take you from “how do AI engines see us?” to published, monitored, and climbing — and you stay in control of every one. Tap any step to see the real modules inside and choose what to switch on.</p>
              <div className="auto-meta">
                <div className="legend" aria-label="Status legend">
                  <span className="legend__item"><span className="legend__dot legend__dot--done" />Complete</span>
                  <span className="legend__item"><span className="legend__dot legend__dot--active" />In progress</span>
                  <span className="legend__item"><span className="legend__dot legend__dot--approval" />Needs you</span>
                  <span className="legend__item"><span className="legend__dot legend__dot--waiting" />Waiting</span>
                </div>
                <div className="auto-progress" role="img" aria-label="Workflow configuration progress">
                  <span><span className="meter__mode">{ctx.workspaceMode === 'agency' ? 'Agency workspace' : 'Client workspace'}</span> · <b>{displayCounts?.percentConfigured || 0}%</b> configured · {countLabel(displayCounts).replace(/ · /g, ' · ')}</span>
                  <span className="auto-progress__bar"><span className="auto-progress__fill" style={{ width: `${displayCounts?.percentConfigured || 0}%` }} /></span>
                </div>
              </div>
              <div className="auto-actions">
                <Btn kind="ghost" icon="refresh" sm onClick={refresh} disabled={!run || busy}>Refresh</Btn>
                <Btn icon="play" sm onClick={createRun} disabled={busy}>{run ? 'New run' : 'Create run'}</Btn>
              </div>
            </header>

            <div className="ctxbar" data-role={ctx.workspaceMode} aria-label="Automation run context">
              <div className="ctxbar__main">
                <div className="ctx__field ctx__field--role">
                  <span className="ctx__label">Workspace</span>
                  <div className="role-switch" role="group" aria-label="Workspace">
                    {['client', 'agency'].map((mode) => (
                      <button key={mode} className={'role-switch__opt' + (ctx.workspaceMode === mode ? ' is-on' : '')} type="button" aria-pressed={ctx.workspaceMode === mode}
                        onClick={() => setCtx((current) => ({ ...current, workspaceMode: mode, planKey: mode === 'agency' ? 'agency' : 'growth', clientId: mode === 'agency' ? slug(CTX.client[0]) : 'self' }))}>
                        {mode}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="ctx__field ctx__field--agency">
                  <span className="ctx__label">Client</span>
                  <div className="ctx__select"><select value={ctx.clientId} onChange={(e) => setCtx((current) => ({ ...current, clientId: e.target.value }))}>{CTX.client.map((item) => <option key={item} value={slug(item)}>{item}</option>)}</select></div>
                </div>
                <div className="ctx__field">
                  <span className="ctx__label">Website</span>
                  <div className="ctx__select"><select value={ctx.websiteId} onChange={(e) => setCtx((current) => ({ ...current, websiteId: e.target.value, websiteUrl: `https://${e.target.value}` }))}>{CTX.website.map((item) => <option key={item} value={slug(item)}>{item}</option>)}</select></div>
                </div>
                <div className="ctx__field">
                  <span className="ctx__label">Audit</span>
                  <div className="ctx__select"><select value={ctx.auditId || slug(CTX.audit[0])} onChange={(e) => setCtx((current) => ({ ...current, auditId: e.target.value }))}>{CTX.audit.map((item) => <option key={item} value={slug(item)}>{item}</option>)}</select></div>
                </div>
                <div className="ctx__field ctx__field--agency">
                  <span className="ctx__label">Recipe</span>
                  <div className="ctx__select"><select value={ctx.recipeId || ''} onChange={(e) => setCtx((current) => ({ ...current, recipeId: e.target.value || null }))}>{CTX.recipe.map((item, index) => <option key={item} value={index ? slug(item) : ''}>{item}</option>)}</select></div>
                </div>
                <div className="ctx__field ctx__field--client">
                  <span className="ctx__label">Plan</span>
                  <div className="ctx__select"><select value={ctx.planKey} onChange={(e) => setCtx((current) => ({ ...current, planKey: e.target.value }))}><option value="growth">Growth</option><option value="enterprise">Enterprise</option></select></div>
                </div>
                <div className="ctx__field ctx__field--agency ctx__field--planchip">
                  <span className="ctx__label">Plan</span>
                  <span className="ctx__chip">Agency · all entitlements</span>
                </div>
              </div>
              <p className="ctx__scope">{ctxScope}</p>
            </div>

            {error && <div className="js-gap sev-high auto-error"><h4><Icon name="alert" size={16} />Automation action failed</h4><p>{error}</p></div>}

            <section className="flow-stage" aria-label="Automation process flow">
              <div className={'flow' + (focus ? ' has-focus' : '')}>
                {STAGES.map((item, index) => {
                  const itemStatus = stageStatus(run, item.id);
                  const meta = STATUS[itemStatus] || STATUS.locked;
                  return (
                    <React.Fragment key={item.id}>
                      <button className={'node' + (focus === item.id ? ' is-focused' : '')} type="button" data-stage={item.id} data-status={itemStatus} data-shape="round" style={{ '--accent': item.accent }} aria-pressed={focus === item.id} onClick={() => setFocus(item.id)}>
                        <span className="node__num">STEP {item.num}</span>
                        <span className="node__tile">
                          <span className="node__ring" />
                          <span className="node__orbit" aria-hidden="true" />
                          <span className="node__halo" aria-hidden="true" />
                          <span className="node__emblem"><img src={item.img} alt="" /></span>
                          <span className="node__badge"><Icon name={meta.icon} size={15} /></span>
                        </span>
                        <span className="node__head">
                          <span className="node__title">{item.title}</span>
                          <span className="node__desc">{item.desc}</span>
                          <span className={'pill ' + meta.pill}><span className="dot" />{meta.label}</span>
                        </span>
                      </button>
                      {index < STAGES.length - 1 && (
                        <div className="connector" data-flow={connectorState(run, index)}>
                          <div className="connector__track">
                            <div className="connector__fill" />
                            {['paused', 'idle'].includes(connectorState(run, index)) ? (
                              <div className="connector__flag"><Icon name={connectorState(run, index) === 'paused' ? 'alert' : 'shield'} size={12} />{connectorState(run, index) === 'paused' ? 'Awaiting approval' : 'Unlocks at publish'}</div>
                            ) : (
                              <>
                                <span className="connector__dot" /><span className="connector__dot" /><span className="connector__dot" />
                              </>
                            )}
                          </div>
                        </div>
                      )}
                    </React.Fragment>
                  );
                })}
              </div>

              {!run && <p className="panel__hint">Create a run to persist context, module selections, approvals, publish jobs, monitoring plans, and events through the backend.</p>}

              <div className="panel is-open" aria-live="polite">
                <div className="panel__card" style={{ '--accent': stage.accent }}>
                  <div className="panel__top">
                    <span className="panel__icon"><img src={stage.img} alt="" /></span>
                    <div className="panel__heading">
                      <div className="panel__kicker">STEP {stage.num} · <span style={{ color: 'var(--accent)' }}>{status.label}</span></div>
                      <h2 className="panel__title">{stage.title}</h2>
                      <p className="panel__blurb">{stage.blurb}</p>
                    </div>
                    <span className={'pill ' + status.pill} style={{ flex: '0 0 auto' }}><span className="dot" />{status.label}</span>
                  </div>
                  <div className="panel__body">
                    {stage.id === 'publish' && (
                      <div className="panel__targets">
                        <span className="panel__targets-label">Destinations</span>
                        <div className="targets">
                          {(run?.publishTargets || safeRegistry.publishTargets || []).map((target) => (
                            <span className={'target ' + targetClass(target.status)} key={target.id}>
                              <span className="target__dot" />{target.label}<span className="target__state">{target.status}</span>
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                    <div className="panel__bodyhead">
                      <h3>What runs in this step</h3>
                      <span className="panel__count">{countLabel(displayCountsByStep[stage.id])}</span>
                    </div>
                    <div className="checklist">
                      {items.length ? items.map((item) => {
                        const meta = moduleMeta(safeRegistry, item.moduleKey);
                        const locked = !['selected', 'available', 'complete'].includes(item.state);
                        const chip = stateChip(item.state);
                        return locked ? (
                          <div className="check is-disabled" key={item.moduleKey}>
                            <span className="check__box check__box--lock"><Icon name={chip?.icon || 'shield'} size={12} /></span>
                            <span className="check__text"><span className="check__label">{meta.label || item.moduleKey}</span><span className="check__desc">{meta.description || item.blockingReason || item.moduleKey}</span></span>
                            {chip && <span className={'tag ' + chip.cls}>{chip.text}</span>}
                          </div>
                        ) : (
                          <button className={'check' + (item.selected || item.state === 'complete' ? ' is-on' : '')} type="button" role="checkbox" aria-checked={Boolean(item.selected)} key={item.moduleKey} onClick={() => run && toggleItem(item)} disabled={!run || busy || item.state === 'complete'}>
                            <span className="check__box"><Icon name="check" size={13} /></span>
                            <span className="check__text"><span className="check__label">{meta.label || item.moduleKey}</span><span className="check__desc">{meta.description || item.lastRunSummary?.outputType || 'Ready for this run context.'}</span></span>
                            {meta.scope === 'agency' && <span className="tag tag--agency">Agency</span>}
                            {item.state === 'complete' && <span className="tag tag--agency">Complete</span>}
                          </button>
                        );
                      }) : (safeRegistry.modules || []).filter((item) => item.step === stage.id).map((item) => {
                        const chip = stateChip(item.state);
                        const locked = !['selected', 'available'].includes(item.state);
                        return locked ? (
                          <div className="check is-disabled" key={item.moduleKey}>
                            <span className="check__box check__box--lock"><Icon name={chip?.icon || 'shield'} size={12} /></span>
                            <span className="check__text"><span className="check__label">{item.label}</span><span className="check__desc">{item.description}</span></span>
                            {chip && <span className={'tag ' + chip.cls}>{chip.text}</span>}
                          </div>
                        ) : (
                          <div className={'check' + (item.state === 'selected' ? ' is-on' : '')} key={item.moduleKey}>
                            <span className="check__box"><Icon name="check" size={13} /></span>
                            <span className="check__text"><span className="check__label">{item.label}</span><span className="check__desc">{item.description}</span></span>
                            {item.scope === 'agency' && <span className="tag tag--agency">Agency</span>}
                          </div>
                        );
                      })}
                    </div>
                    <div className="panel__foot">
                      <span className="panel__note">
                        {stage.id === 'approve' ? <span className="pill pill--amber"><span className="dot" />{run?.approvalSummary?.approved || 0}/{run?.approvalSummary?.required || 0} approved</span> :
                          stage.id === 'publish' ? <span className="pill pill--coral"><span className="dot" />{canPublish ? 'Ready to publish' : 'Blocked until approval completes'}</span> :
                          stage.id === 'monitor' ? <span className="pill pill--coral"><span className="dot" />{canMonitor ? 'Monitoring can start' : 'Unlocks once Step 04 publishes'}</span> :
                          <span className="pill pill--lime"><span className="dot" />Backend-resolved module state</span>}
                      </span>
                      <div className="panel__actions">
                        <Btn kind="ghost" sm onClick={() => setFocus(STAGES[Math.max(0, STAGES.findIndex((item) => item.id === stage.id) - 1)].id)}>Previous step</Btn>
                        {stage.id === 'approve' ? (
                          <Btn sm kind="gold" icon="check" onClick={() => act('approve-all', approveAll)} disabled={!run || busy || !run.generatedAssets?.length || run.approvalSummary?.complete}>Approve all</Btn>
                        ) : stage.id === 'publish' ? (
                          <Btn sm icon="download" onClick={() => act('publish', () => automationApi().publish(run.id, { targetId: 'static_export', mode: 'dry_run', acceptedAsBaseline: true }))} disabled={!run || busy || !canPublish}>Static export</Btn>
                        ) : stage.id === 'monitor' ? (
                          <Btn sm icon="activity" onClick={() => act('monitor', () => automationApi().startMonitoring(run.id, { cadence: 'weekly' }))} disabled={!run || busy || !canMonitor}>Start monitoring</Btn>
                        ) : (
                          <Btn sm icon="play" onClick={() => run ? startStep(stage.id) : createRun()} disabled={busy}>{run ? `Start ${stage.title}` : 'Create run'}</Btn>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </section>
          </div>
        </main>
      </div>
    );
  }

  window.AutomationView = AutomationView;
})();
