DreamLayers Site Clarity — Website Growth Intelligence System
=====================================================================

1. VISION
---------
A WordPress plugin that turns a raw site audit into a single, business-
focused decision for the site owner. Instead of showing 17 checkboxes,
WCL tells the user:

  "Here is what is broken, how much it costs you, and what you gain if fixed."

The system:
  • Runs a technical audit (SEO, security, performance, content, config)
  • Converts raw checks into business-meaningful issues
  • Attaches per-issue impact_data (traffic / conversion / SEO / risk + score)
  • Computes site-level "Growth Leak" loss metrics
  • Simulates before/after score and gains for every fix
  • Picks ONE primary action by business impact_score (severity × weight × fix-ease)
  • Lets the user fix it with one click (auto) or numbered steps (manual)
  • Tracks the full lifecycle: detected → in_progress → fixed → verified
  • Re-audits automatically after every fix
  • Surfaces a Weekly Growth Summary (fixes applied + score trend)
  • Supports "focus mode" (traffic / leads / SEO / health) for priority boost

Core philosophy: one screen, one decision, one action — driven by business
impact, not technical noise.

2. CURRENT FEATURES (Working)
-----------------------------

A. Site Audit (17 checks)
   ssl, search_visibility, permalinks, tagline, site_title, sitemap, robots,
   admin_email, user_registration_safety, wp_version, php_version, cache_plugin,
   seo_plugin, security_plugin, form_plugin, homepage, image_alt_coverage

B. 4-Layer Architecture (strict separation enforced)
   Layer 1 — Raw Checks        (WCL_Site_Audit)         internal only; TRUE=pass, FALSE=fail/warn
   Layer 2 — Impact Engine     (WCL_Impact_Engine)      attaches impact_data, simulation, site loss
   Layer 3 — Issue Generator   (WCL_Issue_Generator)    user-facing issues enriched by Impact Engine
   Layer 4 — Fix Registry      (WCL_Fix_Registry)       maps issue_key → WP action or manual steps

B0. Plan System — DISABLED (everything is free)
   WCL_Plan still exists for backward compat. All gating is bypassed:
     • can( $feature ) → always true
     • current() → always 'pro'
     • is_pro() → always true
   No Free/Pro UI distinction. No upgrade prompts. All features unlocked.

B1. Impact Engine (NEW core layer)
   • catalogue() — per-issue impact profile
     (traffic_impact, conversion_impact, seo_impact, fix_ease,
      traffic_loss_pct, lead_loss_pct, seo_loss_pct,
      business_message, loss_estimation, gain_estimation, urgency_reason)
   • compute_score(issue, impact) — impact_score (0-100) using
     severity_multiplier × weight × (1 + 0.4 × fix_ease)
   • enrich_issue(issue) — attaches impact_data + flat business fields
   • site_loss(issues) — aggregated Growth Leak with severity + summary
   • simulate_fix(issue, current_score) — before/after score & gain preview
   • weekly_summary() — fixes-this-week count + score trend

C. Issue State Machine
   States: detected → in_progress → fixed → verified → regressed
   Stored in wp_wcl_issue_states (DB table with UNIQUE KEY on issue_key)
   Transition validation prevents illegal jumps
   sync_from_audit() auto-updates states after every audit run

D. Execution Engine
   WCL_Execution_Engine runs fixes, tracks pre-fix score, re-audits, returns
   old_score, new_score, score_change, primary action, state badge,
   site_loss (Growth Leak refresh), progress metrics
   • undo_last() — rolls back the most recent fix via WCL_Fix_Log (Pro)

D1. Fix Log + Rollback (NEW)
   wp_wcl_fix_log table stores every fix execution:
   id, issue_key, fix_action, status, message, changes (json),
   confidence, executed_at, rolled_back_at
   • record() — write change history on every successful fix
   • last_undoable() — fetch the most recent non-rolled-back entry
   • rollback(log_id) — reapply old values from changes[]
   • recent(limit) — fix history list (Pro UI)

D2. Fix Confidence Levels
   Every registry entry now declares:
   • confidence : safe | medium | risky (used for ordering / logging)
   • option_keys : declares which WP options the fix mutates
     (used to record before/after for rollback)

D3. Direct-Action Routing (NEW)
   Every manual issue in the Fix Registry now has:
     • manual_url   — a real WordPress admin deep link
                      (plugin install search, settings page, etc.)
     • action_label — short CTA text ("Install Yoast SEO",
                      "Open Reading Settings", etc.)
   When the primary issue is manual, the dashboard renders a
   prominent "<action_label> →" button that opens the right
   WordPress screen in a new tab. Step-by-step instructions move
   into a small collapsible expander under the button.
   Coverage:
     ssl              → Plugins ▸ Really Simple SSL
     sitemap / robots → Plugins ▸ Yoast SEO
     seo_plugin       → Plugins ▸ Yoast SEO
     security_plugin  → Plugins ▸ Wordfence
     cache_plugin     → Plugins ▸ W3 Total Cache
     form_plugin      → Plugins ▸ WPForms
     site_title       → Settings ▸ General (#blogname)
     admin_email      → Settings ▸ General (#admin_email)
     homepage         → Settings ▸ Reading
     wp_version       → Dashboard ▸ Updates
     php_version      → Tools ▸ Site Health
     image_alts       → Media library

E. Algorithmic Engine
   get_primary_action() — picks top issue by impact_score > severity > weight > focus boost
   get_all_issues() — returns all real issues for technical details accordion
   Now exposes impact_data, business_message, loss_estimation,
   urgency_reason, gain_estimation, and full Impact Engine simulation
   on the primary action object
   fix_action_for() / estimated_effect_for() — static lookup maps

F. Onboarding Flow (rebuilt for clarity)
   Visual stepper at top: Scan → Result → Focus → Ready
   Each step is a single SaaS card with a kicker, headline, lead copy
   and a clear next action. No emoji icons, no jargon.

   Step 1 — Scan: "Scanning your site for growth blockers"
     • Explains what we're doing (17 checks across 4 domains)
     • Animated indeterminate progress bar
     • Decorative checklist pills (SEO & indexing, Security & SSL,
       Performance, Lead capture)
     • Reassures: "We never modify your site during the scan."

   Step 2 — Result: "Here's what we found"
     • 3-up stat grid: health score · critical · warnings
     • "Biggest growth blocker right now" inline card surfaces the
       primary issue title
     • CTA: "Pick my focus →"

   Step 3 — Focus: "What do you want to move first?"
     • 4 goal cards, each with concrete examples of what gets
       prioritized for that goal (e.g. Better SEO → titles,
       permalinks, sitemap, alt text)
     • Click triggers transient "Picking your first action…" state

   Step 4 — Ready: "Your first move is queued up"
     • Surfaces the goal-adjusted primary action title
     • Explains what they'll see on the dashboard (cost + gain + CTA)
     • CTA: "Open my dashboard →"

G. Dashboard (Growth Intelligence SaaS UI)
   STRICT VISUAL HIERARCHY (top → bottom):
     1. Brand header (eyebrow "Growth Intelligence" + benchmark + plan badge)
     2. Score + Progress (compact context)
     3. PRIMARY DECISION CARD (HERO — the only thing the user must read)
     4. Undo strip (Pro, only when there's a recent fix to roll back)
     5. Supporting context: Growth Leak (Pro) + Weekly Summary
     6. Focus selector (inline)
     7. System Details (collapsed debug layer)

   Brand header (NEW):
     • Eyebrow text: "Growth Intelligence"
     • Title: "Your next move"
     • Benchmark pill: rule-based peer comparison
       (Ahead / On par / Behind similar WordPress sites)
     • Plan badge: FREE / PRO

   Score bar: ring (good/fair/poor) + "Technical health score" label
     + progress bar + "X of Y issues resolved" + explicit hint.

   Undo strip (NEW, Pro): one-click rollback of the last fix with
     plain-language message + confirmation dialog.

   Supporting context (de-emphasized, below the hero):
     • Growth Leak: 3 metrics (Traffic / Leads / SEO) — Pro only.
       Free users see a locked card with contextual upgrade pitch.
     • Weekly Summary: fixes this week + delta vs LAST WEEK
       + score trend + motivational message.
       Free users see a "Get weekly reports →" upgrade link inline.

   Decision card (one primary issue only):
     — Impact pill in meta (Business impact score 0-100)
     — State badge (detected / in_progress / fixed / verified / regressed)
     — Title (human-readable)
     — Business Impact block (NEW):
         · business_message (e.g. "Your site is invisible on Google")
         · "What this is costing you" → loss_estimation
         · "Why it matters now" → urgency_reason
     — Fix Outcome / Before-After block (NEW):
         · current_score → new_score with delta pill
         · gain pills (+% traffic / +% leads / +% SEO)
         · gain_estimation message
     — ONE CTA only:
         · Auto-fix: "Fix automatically" button
         · Manual: "Manual fix required" + numbered fix_steps
   • Loading & state feedback:
     — Skeleton loader shimmer during data transitions
     — "Applying fix…" button state with spinner
     — "Re-checking your system…" intermediate state after fix success
     — Smooth 1.2s transition before new primary card appears
   • Focus selector: inline dropdown to change goal
   • System details: collapsed accordion grouped by 5 categories
     (Security, SEO, Performance, Content, Configuration),
     each with icon + fail/warn count + expandable pass/warn/fail items

H. Data Layer
   • Daily snapshots (wp_wcl_snapshots)
   • Insights (wp_wcl_insights)
   • Health scores (wp_wcl_health_scores)
   • AI results (wp_wcl_ai_results)
   • Issue states (wp_wcl_issue_states)
   • Fix log (wp_wcl_fix_log) — full change history + rollback (NEW)

I. Background Jobs
   • Daily snapshot via cron (wcl_daily_snapshot)
   • Weekly insights (wcl_generate_insights)
   • Weekly email reports (wcl_weekly_email_report)

J. AJAX Endpoints (all in class-wcl-ajax-actions.php)
   wcl_execute_fix_action     — run fix, update state, re-audit, return new primary
                                + site_loss for Growth Leak refresh
   wcl_run_onboarding_scan    — initial scan, return score/counts/primary
   wcl_set_onboarding_goal    — set focus goal, mark onboarding complete
   wcl_refresh_state          — refresh dashboard data without executing fix
   wcl_undo_last_fix (NEW)    — Pro only: roll back the most recent fix
                                via WCL_Fix_Log, re-audit, return new primary

3. WEAK POINTS / BUGS (Current & Historical)
--------------------------------------------

[FIXED] Activation fatal error — missing class requires in activator
[FIXED] Raw checks showing in UI — implemented strict 3-layer separation
[FIXED] Duplicate sync_from_audit() in onboarding AJAX — removed
[FIXED] Onboarding stuck on "Analyzing…" — added onerror/ontimeout/try-catch
[FIXED] Non-static method called statically — fix_action_for() and
          estimated_effect_for() changed to public static
[FIXED] Stale cached score vs fresh issue states — Experience Engine now
          forces run(true) to bypass 1-hour cache on every dashboard load
[FIXED] PHP 8 null foreach in get_all() / get_active_issues() — added
          is_array() guards for when wp_wcl_issue_states table is missing
[FIXED] WCL_Issue_State::update() $format/$data mismatch — replaced fragile
          insert-then-update with explicit exists-check + update/insert

[FIXED] Score vs resolved count UX tension — label now reads
  "Technical health score" with explicit hint:
  "Score = technical audit. Progress = fixes applied."

[FIXED] Misleading audit check labels — removed state-implying words
  from labels (e.g. "Caching enabled" → "Caching plugin") so pass/fail
  is unambiguous regardless of status.

[FIXED] Only one actionable fix visible — Issue Generator was blocking
  5 plugin-related checks (seo_plugin, security_plugin, cache_plugin,
  sitemap, robots) by setting them to null. Added proper issue definitions
  with titles, descriptions, severity, weight, fix steps, and ROI data
  so all checks can become actionable issues.

[FIXED] Onboarding UI rendering issues — removed old conflicting
  onboarding CSS (lines 834-1039) that used different class names than
  the new SaaS onboarding template. New onboarding now renders cleanly
  with stepper, stat grid, goal options, and proper styling.

[FIXED] Manual fixes showing vague single-line text — Issue Generator
  now provides fix_steps (numbered WordPress instructions) for every
  manual issue. Dashboard renders them as an ordered list.

[FIXED] Fake "Fix this now" button on manual issues — manual issues
  now show "Manual fix required" header + steps, never a button.
  Auto issues show "Fix automatically" button.

[FIXED] No loading state during re-audit — dashboard JS now shows
  "Re-checking your system…" spinner for 1.2s after fix success
  before transitioning to the new primary card.

[FIXED] System details accordion was severity-grouped only — now
  grouped by 5 business categories (Security, SEO, Performance,
  Content, Configuration) with per-category status icons and counts.

[REMAINING] Health score history (wp_wcl_health_scores) is written by
  WCL_Scheduler::run_daily_snapshot() which calls WCL_Insight_Engine,
  but the insight engine is NOT the same as the site audit. The health
  score stored in snapshots may not match the live audit score shown on
  the dashboard.

[REMAINING] The onboarding summary step shows "0 critical / 0 warnings"
  during the brief moment before AJAX returns. No skeleton loader.

[REMAINING] If the user is on a slow host, the 30-second AJAX timeout
  in onboarding may still fire. No retry-with-backoff logic.

[REMAINING] Focus mode selector in dashboard has no visual confirmation
  when changed. It submits a POST form and reloads the page, breaking
  the single-page-app feel.

[REMAINING] The technical details accordion shows ALL checks from
  the audit, not just the active (non-fixed) ones. Fixed/verified
  issues still appear in the list.

[REMAINING] No undo / rollback for auto-fixes. If update_option fails
  or has unintended side effects, the user must fix manually.

[REMAINING] No audit history / changelog per issue. The state machine
  tracks timestamps (first_detected_at, fixed_at, regressed_at) but
  there is no UI to view the timeline.

[REMAINING] Email reports reference health scores from the snapshot
  system, which may not reflect the live audit state at send time.

[REMAINING] The AI results table exists but the AI integration is
  mostly a stub for Pro plans. No LLM API calls are wired end-to-end.

[REMAINING] Onboarding summary has no skeleton loader during the
  brief window before scan results return.

4. MISSING FEATURES / ROUTES
----------------------------

A. Missing Auto-Fix Handlers
   The Fix Registry has registry entries for many issues but only a
   few have real execute() handlers:

   WIRED (auto-fix handlers):
     search_visibility  → update_option('blog_public', 1)
     user_registration  → update_option('default_role', 'subscriber')
     permalinks         → update_option('permalink_structure', '/%postname%/')
     tagline            → update_option('blogdescription', '')
     site_title         → update_option('blogname', 'My Site')
     admin_email        → update_option('admin_email', '...')

   MISSING (requires manual steps or host action):
     ssl              → host-level SSL / Let's Encrypt
     sitemap          → install + activate SEO plugin
     robots           → install + activate SEO plugin
     seo_plugin       → install + activate plugin
     security_plugin  → install + activate plugin
     cache_plugin     → install + activate plugin
     form_plugin      → install + activate plugin
     homepage         → create page + update_option('show_on_front', 'page')
     wp_version       → trigger WordPress core update (restricted, risky)
     php_version      → host-level action, cannot be done from PHP
     image_alts       → batch update post_content (complex, risky)

B. Missing UI Routes / Screens
   • Settings page needs visual refresh to match SaaS single-decision theme
   • History / snapshots page — no dedicated view, only in email reports
   • Issue detail page — no deep-dive into a single issue's timeline
   • Bulk actions — no "Mark all as fixed" or "Ignore issue" capability
   • Notifications / toast system — errors show as WordPress admin notices
   • Mobile-responsive polish — dashboard is usable but not optimized

C. Missing API / Data Features
   • REST API endpoints for external dashboards (e.g. SaaS admin panel)
   • Webhook support for Slack/email when state changes
   • Export audit report as PDF
   • Compare two snapshots side-by-side
   • Team/role-based access (only manage_options now)

D. Missing Business Logic
   • Pro plan gate: AI insights, advanced ROI, custom goals
   • Growth plan engine generates a plan but it is NOT surfaced in the
     single-decision UI (it was from an earlier iteration)
   • No lead-capture-to-CRM integration
   • No A/B test suggestions based on audit gaps
   • No competitor gap analysis

5. FILE MAP
-----------

dreamlayers-site-intelligence.php       Main plugin file, constants, loader init
includes/class-wcl-loader.php           Loads all dependencies in correct order
includes/class-wcl-activator.php        Activation: creates tables, runs first audit,
                                        sets cron, migrates legacy states
includes/class-wcl-deactivator.php      Cleanup on deactivation

--- Plan & Monetization ---
includes/class-wcl-plan.php             Free/Pro feature flags + contextual upgrade
                                        labels for moment-of-insight monetization

--- Fix Log / Rollback ---
includes/class-wcl-fix-log.php          wp_wcl_fix_log table I/O: record(),
                                        last_undoable(), rollback(), recent()

--- Audit & Issue Layers ---
includes/class-wcl-site-audit.php       17 raw checks, cached for 1 hour
includes/class-wcl-impact-engine.php    Per-issue impact_data (traffic/conv/SEO/risk),
                                        impact_score, site-level Growth Leak,
                                        before/after fix simulation, weekly summary
includes/class-wcl-issue-generator.php  Converts raw checks → structured issues,
                                        enriched by Impact Engine, sorted by impact_score
includes/class-wcl-algorithmic-engine.php  Primary issue selection, focus boost,
                                            fix_action_for(), estimated_effect_for()
includes/class-wcl-issue-state.php      DB-backed state machine with transition
                                        validation and sync_from_audit()

--- Fix & Execution ---
includes/class-wcl-fix-registry.php       Maps issue_key → executable WP action
includes/class-wcl-execution-engine.php   Runs fix, tracks score, re-audits,
                                          returns response for dashboard JS
includes/class-wcl-fix-executor.php     Legacy fix executor (partially superseded)

--- AJAX ---
includes/ajax/class-wcl-ajax-actions.php  All AJAX handlers: fix, onboarding scan,
                                          set goal, refresh state

--- Experience & Dashboard ---
includes/class-wcl-experience-engine.php  Orchestrates flow state, runs audit + algo
includes/class-wcl-dashboard.php        DB queries for snapshots, health scores,
                                        comparisons, weekly pulse
includes/class-wcl-focus-mode.php       Goal setting, clearing, issue filtering
includes/class-wcl-growth-plan-engine.php  Generates growth plans (not surfaced in UI)
includes/class-wcl-insight-engine.php   Generates insights from metrics
includes/class-wcl-data-collector.php   Collects page views, forms, orders, etc.
includes/class-wcl-email-reports.php    Builds and sends weekly email summaries

--- Admin & UI ---
includes/class-wcl-admin.php            Menu registration, asset enqueue,
                                          admin_post handlers (focus mode form)
admin/dashboard-page.php               Conditional loader: onboarding vs dashboard
templates/onboarding.php                5-step onboarding UI + JS
templates/dashboard.php                 SaaS single-decision dashboard + JS
admin/settings-page.php               Settings form (plan, API key, etc.)

--- Global Helpers ---
includes/class-wcl-global-functions.php  wcl_build_real_issues(), wcl_get_primary_action()

--- Database ---
database/class-wcl-db.php              Schema + maybe_upgrade() for all tables

--- Assets ---
assets/css/admin.css                    All admin styles (SaaS theme, scorebar,
                                        decision card, manual badge, onboarding)
assets/js/dashboard.js                 Minimal plan picker JS (legacy)

6. DATA FLOW (One Fix Cycle)
----------------------------

  User clicks "Fix this now"
    ↓
  JS → AJAX wcl_execute_fix_action (issue_id)
    ↓
  WCL_Execution_Engine::execute()
    • Get current state from wp_wcl_issue_states
    • Transition: detected → in_progress
    • Call WCL_Fix_Registry::execute(issue_id)
        → runs real WP action (update_option, etc.)
    • Transition: in_progress → fixed
    • Run targeted re-audit for the issue's category
    • Run full WCL_Site_Audit::run(true)
    • WCL_Issue_State::sync_from_audit() updates all states
    • Capture old_score, new_score, score_change
    • Recompute primary action via wcl_get_primary_action()
    • Return JSON
    ↓
  JS updates DOM:
    • score number, score bar width
    • fixed count / total count label
    • decision card title, impact, ROI pills
    • state badge color + text
    • button: new "Fix this now" OR manual instruction block
    • success feedback banner with score change arrow

7. NEXT PRIORITIES (Recommended)
--------------------------------
  DONE: Fix inverted logic in raw checks (TRUE=pass, FALSE=fail/warn)
  DONE: Add fix_steps to Issue Generator for all manual issues
  DONE: Separate score vs progress with clear labels and hints
  DONE: Add skeleton loaders, re-checking state, and smooth transitions
  DONE: Group system details by business category (Security, SEO, etc.)
  DONE: Fix misleading audit check labels
  DONE: Build WCL_Impact_Engine (impact_data, site loss, simulation)
  DONE: Sort issues by impact_score in Issue Generator
  DONE: Dashboard Business Impact block (loss + urgency)
  DONE: Dashboard Fix Outcome before/after preview block
  DONE: Dashboard Growth Leak site-level loss block
  DONE: Dashboard Weekly Growth Summary block
  DONE: Plan system (Free/Pro feature flags + contextual upgrades)
  DONE: Fix confidence levels (safe / medium / risky)
  DONE: Fix Log (wp_wcl_fix_log) capturing before/after for every fix
  DONE: Undo last fix (AJAX wcl_undo_last_fix, Pro feature)
  DONE: Week-over-week fixes delta in Weekly Summary
  DONE: Rule-based peer benchmark pill in brand header
  DONE: Brand header + product positioning shift to "Growth Intelligence"
  DONE: Enforce strict visual hierarchy (Primary card = hero, everything else supports)
  DONE: Direct-action routing — every manual issue opens the right WP screen
  DONE: Onboarding rebuilt with stepper, clear narrative, concrete copy
  DONE: Plan tiers removed — every feature is free

  1. Wire remaining auto-fix handlers (homepage, wp_version if safe)
  2. Add REST API endpoints for external dashboards
  3. Surface the Growth Plan Engine in the dashboard UI
  4. Add issue timeline / changelog view
  5. Make focus mode selector AJAX-powered (no page reload)
  6. Add onboarding skeleton loader for scan results
  7. Implement Pro plan gating for AI insights and advanced features
  8. Add "Ignore this issue" / snooze capability
  9. Export audit report as PDF
 10. Add retry-with-backoff for slow-host onboarding timeouts
 11. Replace heuristic loss percentages with real analytics when available
     (data-collector hooks already exist)
