import React, { CSSProperties, useMemo } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import DOMPurify from 'dompurify';
import { stableHash } from '../../utils/escape';
import { scopeCss } from '../../utils/scope-css';

interface HtmlBlockProps {
  code: string;
  style?: CSSProperties;
  aiName?: string;
  node_id?: string;
}

// Task 24: widening the allow-list after a customer's broad HTML fixture
// showed 38% of it silently deleted (tables losing colspan/rowspan/scope,
// <dl>/<sub>/<details>/inline <svg>/<video>/<audio> dropped wholesale,
// lang/dir/role stripped, <ol start/reversed> flattened). The owner's call:
// be generous -- this block is an explicit escape hatch and customers
// reasonably expect it to render ordinary HTML, including forms. The four
// non-negotiables (no <script>, no on*, no javascript: URLs, iframes stay
// sandboxed) are unaffected by the widening and are covered by dedicated
// tests in HtmlBlock.test.ts / HtmlBlock.security.test.ts.
const PURIFY_CONFIG = {
  ALLOWED_TAGS: [
    'a','p','br','hr','div','span','section','article',
    'header','footer','main','aside','nav',
    'ul','ol','li',
    'h1','h2','h3','h4','h5','h6','hgroup',
    'em','strong','b','i','u','s',
    'blockquote','code','pre',
    'img','figure','figcaption',
    'iframe',
    // Tables: pasted content commonly includes these; dropping them
    // silently ate customer-pasted tables (see C1 review finding).
    'table','thead','tbody','tfoot','tr','td','th','caption','colgroup','col',
    // Text semantics (Task 24).
    'sub','sup','small','mark','del','ins','abbr','cite','q','time','data',
    'kbd','samp','var','dfn','address','bdi','bdo','ruby','rt','rp','wbr',
    // Lists (Task 24).
    'dl','dt','dd','menu',
    // Disclosure widget (Task 24). Note: <dialog> and <template> are
    // deliberately NOT added -- the fixture exercises them wrapped in
    // on*= handlers specifically to prove they still get neutralized/
    // dropped by staying outside the allow-list.
    'details','summary',
    // Media (Task 24). URL-bearing attributes on these (poster, srcset,
    // action, cite...) go through the ALLOWED_URI_REGEXP gate like
    // everything else -- see _isValidAttribute in dompurify, which
    // URI-checks every allowed attribute value except a small fixed
    // "inert" list (alt, class, id, style, title, ...) that never includes
    // src/poster/srcset. The one exception: `src` itself on img/video/
    // audio/source/image/track is additionally covered by DOMPurify's own
    // `DATA_URI_TAGS` allow-list, which accepts any data: URI on those
    // tag/attribute pairs regardless of mimetype, bypassing this regex --
    // see the ALLOWED_URI_REGEXP comment below and
    // HtmlBlock.security.test.ts. Not a gap in the four non-negotiables:
    // none of those tags execute their src as a document.
    'picture','source','video','audio','track','canvas',
    // Forms (Task 24). Site owner's explicit decision: allow the full
    // ordinary form surface. No on*= survives (FORBID_ATTR below), and
    // action/formaction-style URLs are gated by ALLOWED_URI_REGEXP the
    // same as href/src, so `javascript:` still cannot survive here either.
    'form','input','button','select','option','optgroup','textarea',
    'label','fieldset','legend','datalist','output','progress','meter',
    // Inline SVG (Task 24) -- see the block comment on IFRAME_SANDBOX_HOOK's
    // neighbor below for why this is an explicit tag list rather than
    // DOMPurify's USE_PROFILES svg profile. Deliberately excludes <use> and
    // <image> (both need xlink:href, an external-reference vector DOMPurify
    // itself excludes from its own SVG defaults) and <a>/<foreignObject>
    // (not needed by the fixture; foreignObject can embed arbitrary HTML).
    'svg','g','defs','symbol','title','desc','rect','circle','ellipse',
    'line','polyline','polygon','path','text','tspan',
    'lineargradient','radialgradient','stop','clippath','mask','marker',
    'pattern','switch','view',
    // Task 25: block-scoped <style> support. Formerly in FORBID_TAGS
    // (stripped entirely). Now allowed through sanitisation -- its CSS is
    // rewritten by scopeStyleBlocks()/scopeCss() below, immediately after
    // DOMPurify runs, so it can only match inside this block's own wrapper
    // element. See the FORCE_BODY comment below and scopeStyleBlocks() for
    // why allowing the tag alone is not sufficient.
    //
    // Review note (Task 25 follow-up, documented not fixed): DOMPurify's
    // SAFE_FOR_XML default (on unless a caller explicitly disables it,
    // which PURIFY_CONFIG does not) silently drops an ENTIRE <style>
    // element -- not just the offending part -- if its text content
    // contains anything that merely LOOKS tag-like (a `<` followed by a
    // word character, `/`, or `!`), as an mXSS-namespace-confusion defense
    // that isn't specific to <style>. So `.x::after{content:"<Read
    // More>"}` -- a plausible, entirely benign real-world CSS content
    // string -- makes the whole style block vanish with no error, the same
    // way a `<script>` would. This is a GOOD security property (better
    // paranoid than exploitable), but it's an undocumented interaction
    // with this newly-widened surface that will otherwise confuse whoever
    // debugs the inevitable "my CSS just disappeared" report -- confirmed
    // empirically against dompurify+jsdom directly, not guessed at.
    'style',
  ],
  // NOTE: supplying ALLOWED_ATTR replaces DOMPurify's own default attribute
  // allowlist rather than extending it, so anything the product needs
  // (style, id, ...) must be listed explicitly here even though DOMPurify
  // would allow it by default.
  ALLOWED_ATTR: [
    'href','src','alt','title','target','rel',
    'width','height','class','id','style',
    'allowfullscreen','allow','frameborder',
    'sandbox','referrerpolicy',
    // Task 24 additions.
    'colspan','rowspan','scope','headers','span','start','reversed',
    'type','value','name','placeholder','required','disabled','readonly',
    'checked','selected','multiple','size','min','max','step','minlength',
    'maxlength','pattern','rows','cols','accept','action','method','for',
    'list','label','datetime','cite','lang','dir','role','srcset','media',
    'sizes','loading','controls','poster','loop','muted','autoplay',
    'preload','playsinline','kind','srclang','default','open','download',
    'hidden','contenteditable',
    // Bug fix: <select size="4">/<input size> and <meter low/high/optimum>
    // were still being stripped even though <select>/<meter> are already in
    // ALLOWED_TAGS -- only these four attribute names were missing here.
    // Effect: a multi-select rendered at default height instead of the
    // requested row count, and <meter> lost its threshold-based gauge
    // colouring. Pure presentation/semantic attributes -- no URL, no
    // script, no event-handler surface -- so no security weight added.
    'low','high','optimum',
    // SVG presentation attributes (explicit route -- see ALLOWED_TAGS
    // comment on the SVG tag list). Covers the fixture's <svg viewBox
    // role>/<rect>/<circle>/<text> block plus the common presentation
    // attributes for the shapes/gradients allowed above. Deliberately
    // excludes xlink:href (no <use>/<image> allowed, so it has nothing
    // legitimate to attach to) and the SMIL/animation attributes (begin,
    // dur, repeatCount, ...) which DOMPurify's own SVG defaults exclude
    // for the same reason on* handlers are excluded.
    'viewbox','cx','cy','r','rx','ry','x','y','x1','y1','x2','y2',
    'points','d','fill','stroke','stroke-width','stroke-linecap',
    'stroke-linejoin','stroke-dasharray','fill-rule','clip-rule','opacity',
    'fill-opacity','stroke-opacity','text-anchor','dominant-baseline',
    'font-family','font-size','font-weight','transform','offset',
    'stop-color','stop-opacity','gradientunits','gradienttransform',
    'preserveaspectratio',
  ],
  // Review fix (Task 24 follow-up): the data:image arm used to sit inside
  // the group that gets a trailing `:` appended for every alternative
  // (`(?:https?|mailto|tel|data:image\/[a-z]+;base64,):`), so it required
  // a SECOND colon after the one already in "base64,figure" -- no real
  // data URI has that, so the clause could never match. It is now its own
  // top-level alternative. NOTE: this regex is not the only thing gating
  // data: URIs -- DOMPurify has its own internal `DATA_URI_TAGS` allow-list
  // (img/video/audio/source/image/track) that accepts ANY data: URI on
  // those tag/attribute pairs regardless of declared mimetype, bypassing
  // this regex entirely. See HtmlBlock.security.test.ts for a regression
  // test documenting that (acceptable: none of those tags execute their
  // src as a document in mainstream browsers, and <iframe> -- which would
  // be dangerous -- is correctly not in that DOMPurify list).
  ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel):|data:image\/[a-z]+;base64,|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
  // form/input/button/select/textarea removed from FORBID_TAGS (Task 24) --
  // they are now deliberately allowed above. script/object/embed/link/meta
  // stay forbidden. <style> (Task 25) is now allowed too -- see ALLOWED_TAGS
  // comment above and scopeStyleBlocks() below; it survives sanitisation
  // here but its CSS gets scoped afterwards, including copies nested inside
  // the newly-allowed inline <svg> (querySelectorAll('style') in
  // scopeStyleBlocks() doesn't care about namespace/nesting depth).
  FORBID_TAGS: ['script','object','embed','link','meta'],
  FORBID_ATTR: [/^on/i],
  // NOTE: FORCE_BODY is deliberately NOT set here -- see
  // needsForceBody()/purifyHtml() below. It's applied conditionally, per
  // call, only when the input actually has a real <style> tag to rescue.
};

// Task 25: without FORCE_BODY, DOMPurify parses `input` as a full (mini)
// HTML document via DOMParser and only serializes <body>'s contents. Per
// the HTML5 parsing algorithm, a tag that can only legally appear in
// <head> -- and now that <style> is allowed, that includes <style> --
// gets implicitly placed in <head> when it appears before any other real
// content, and is silently lost (DOMPurify never looks at <head>). A block
// whose entire `code` is `<style>h1{color:red}</style>` -- a very
// plausible paste, style-before-markup is a common snippet shape -- would
// vanish with no error anywhere, despite <style> sitting right there in
// ALLOWED_TAGS. FORCE_BODY prepends an internal element before parsing so
// the parser is already in body-insertion-mode by the time it reaches the
// customer's first tag, keeping a leading <style> (or anything else) in
// <body> where DOMPurify's body-only serialization actually looks.
// Confirmed empirically against dompurify+jsdom directly (not just this
// app's behavior) -- see the "leading <style> with nothing before it" test
// in HtmlBlock.test.ts.
//
// Review finding (Task 25 follow-up): FORCE_BODY is NOT a no-op for input
// that has no <style> tag at all. It also changes how the HTML parser
// treats character content sitting between a LEADING comment and the next
// real tag -- normal parsing (before <body> is established) silently drops
// pure-whitespace text runs there per the HTML5 "before head" insertion
// mode rules, while FORCE_BODY (already in body-insertion-mode from the
// first token) preserves that whitespace as a real text node. Concretely:
// a block starting with a multi-line HTML comment -- this repo's own
// ~16KB fixture does exactly that -- gained 2 extra leading bytes (a
// preserved newline) once FORCE_BODY was unconditionally on, which
// silently broke the "blocks without <style> are byte-identical to
// pre-Task-25 output" guarantee (confirmed with a raw diff against
// HtmlBlock.tsx@6a9b227 -- the commit immediately before this task -- over
// the fixture and a comment-led block; see HtmlBlock.test.ts). Fix: only
// ever set FORCE_BODY when the input has a real <style> tag to rescue --
// the one and only case that needs it -- so every other input takes
// exactly the pre-Task-25 code path, unchanged.
//
// "Real" deliberately excludes a `<style` substring that only appears
// inside an HTML comment (e.g. a customer's own code-sample text
// mentioning `<style>`) -- that text can never become an actual <style>
// element, but naively substring-matching it would still flip FORCE_BODY
// on and reintroduce the exact same whitespace-preservation side effect
// for a block that never had, and never needed, real style scoping.
const STYLE_TAG_RE = /<style[\s>/]/i;
const HTML_COMMENT_RE = /<!--[\s\S]*?-->/g;
function needsForceBody(input: string): boolean {
  return STYLE_TAG_RE.test(input.replace(HTML_COMMENT_RE, ''));
}

// M-6: `<iframe>` is allowed (maps/video embeds are a legitimate use case)
// but an iframe with a `src` and NO `sandbox` attribute is a clickjacking/
// phishing vector (DOMPurify already strips <script>/on*=, but an
// unsandboxed iframe still gets full script execution, same-origin-ish
// access via document.domain tricks, top-level navigation, etc., inside
// itself). This hook force-sets a restrictive sandbox on every iframe that
// survives sanitization, keeping `allow-scripts`/`allow-same-origin`/
// `allow-popups`/`allow-forms` (needed for interactive maps/video/oauth
// popups) but deliberately omitting `allow-top-navigation` so an embedded
// page can never redirect/hijack the parent tab.
const IFRAME_SANDBOX_HOOK = (node: Element): void => {
  if (node.nodeName === 'IFRAME') {
    node.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups allow-forms');
    node.setAttribute('referrerpolicy', 'no-referrer');
  }
};

/**
 * Task 25: rewrite any surviving `<style>` element(s) in `sanitized` (the
 * DOMPurify output) so their CSS only matches inside this block's own
 * wrapper element, then wrap the whole thing in that wrapper.
 *
 * Deliberately does the LEAST work possible when there's nothing to scope:
 * a cheap substring check bails out before touching the DOM at all, so a
 * block that doesn't use <style> -- i.e. every block saved before this task
 * -- gets `sanitized` back completely unchanged (same string, no wrapper,
 * no re-serialization round-trip that could subtly reformat attributes).
 * That byte-for-byte identity is a hard requirement: published pages
 * already contain `toHtml()` output with NO wrapper element, and adding one
 * unconditionally would silently change the DOM/box-model of every
 * existing customer block. See HtmlBlock.test.ts's
 * "blocks without <style> are byte-identical" tests, which run this
 * against real fixture content and diff the exact string.
 *
 * Scope identifier: `whp-html-${stableHash(rawCode)}` -- `stableHash` is
 * the existing djb2 hash from utils/escape.ts (already used for this exact
 * class of problem, see `scopeId` in that file), applied to `rawCode` --
 * the block's own `code` prop, nothing else. Pure function of the block's
 * own content: no Math.random, no Date.now, no counter, and deliberately
 * NOT the Craft node id (unlike `scopeId`), because a scope identifier that
 * depends on anything outside `code` would make the editor canvas preview
 * (which calls purifyHtml(code) on render) and the published output (which
 * calls the same purifyHtml(code) at publish time) diverge whenever that
 * outside thing differs between the two call sites, and would make the
 * stored HTML churn on every save even when the block's own content didn't
 * change. Hashing `code` guarantees purifyHtml(code) is fully deterministic
 * on its own -- same code in, byte-identical output out, every time, in
 * both places it's called.
 */
const SCOPE_CLASS_RE = /^whp-html-[0-9a-z]+$/;

/**
 * Idempotency (review finding, Task 25 follow-up): `purifyHtml()` is not
 * reachable-with-its-own-output through any CURRENT code path, but nothing
 * stops a customer from pasting previously-published or exported HTML from
 * this exact feature into a fresh Custom HTML block -- at which point
 * `code` already contains our own `<div class="whp-html-OLD">...<style>
 * .whp-html-OLD h1{...}</style>...</div>` wrapper. Without this check,
 * `scopeStyleBlocks` would hash the NEW `code` to a NEW scope class, fail
 * to recognise the embedded selectors as already scoped (they're prefixed
 * for the OLD class, not the new one `scopeCss`'s own idempotency guard
 * checks against), and nest a second wrapper div around the first while
 * re-prefixing every selector under the new class on top of the old one.
 *
 * Detects "the sanitized content IS ALREADY exactly one of our own scoped
 * wrappers": a single root element, a <div>, whose class matches our own
 * naming convention, and whose `<style>` descendant(s) are each already a
 * no-op under `scopeCss` for that div's own class -- i.e. re-scoping would
 * change nothing. That last check reuses `scopeCss`'s own idempotency
 * guarantee (`scopeCss(scopeCss(x, S), S) === scopeCss(x, S)`, proved in
 * scope-css.test.ts) rather than re-implementing "is this CSS already
 * scoped" as a second parser: if scoping again under the div's own class
 * is a no-op, the CSS is already confined to that div, regardless of
 * whether this app was the one that put it there -- which is the actual
 * safety property this function exists to guarantee, not merely a proxy
 * for it.
 */
function isAlreadyScoped(container: HTMLElement): boolean {
  if (container.children.length !== 1) return false;
  const root = container.children[0];
  if (root.tagName !== 'DIV') return false;
  const cls = root.getAttribute('class') || '';
  if (!SCOPE_CLASS_RE.test(cls)) return false;

  const scopeSelector = `.${cls}`;
  const styleEls = Array.from(root.querySelectorAll('style'));
  if (styleEls.length === 0) return false; // matches our naming by coincidence but scopes nothing -- not ours to protect

  return styleEls.every((el) => {
    const text = el.textContent || '';
    if (text.trim() === '') return true;
    return scopeCss(text, scopeSelector) === text;
  });
}

function scopeStyleBlocks(sanitized: string, rawCode: string): string {
  if (!sanitized.includes('<style')) return sanitized;

  const container = document.createElement('div');
  container.innerHTML = sanitized;

  if (isAlreadyScoped(container)) return sanitized;

  const styleEls = Array.from(container.querySelectorAll('style'));
  const nonEmpty = styleEls.filter((el) => (el.textContent || '').trim() !== '');
  if (nonEmpty.length === 0) return sanitized;

  // Review note (Task 25 follow-up, documented not fixed): `stableHash` is
  // a 32-bit djb2 hash, so it's brute-forceable in principle -- a customer
  // could deliberately craft a second block's `code` to collide onto the
  // same `whp-html-<hash>` class as an existing block on the same page, at
  // which point the two blocks' <style> rules apply to (and override) each
  // other, since they'd share one wrapper class. Impact is CSS-only --
  // visual breakage, never script execution or data exposure -- the same
  // trust tier as other accepted risks in this file (e.g. remote url() in
  // style content, or the pre-existing DATA_URI_TAGS mimetype-blindness
  // documented in HtmlBlock.security.test.ts). Not fixed here: closing it
  // would mean either a wider hash (cheap, but every existing scope class
  // set with THIS Task 25 code would silently reshuffle -- a similar
  // "changing the hash function reshuffles stored HTML" cost the pinned
  // hash test above already guards against happening BY ACCIDENT) or a
  // collision-checked/salted scheme, either of which is a bigger design
  // decision than a follow-up-review fix.
  const scopeClass = `whp-html-${stableHash(rawCode)}`;
  for (const el of nonEmpty) {
    el.textContent = scopeCss(el.textContent || '', `.${scopeClass}`);
  }

  return `<div class="${scopeClass}">${container.innerHTML}</div>`;
}

export function purifyHtml(input: string): string {
  // Hook is added immediately before sanitize() and removed immediately
  // after, scoped tightly to this single call -- so it can never leak onto
  // (or accumulate duplicate copies across) any other DOMPurify.sanitize()
  // call elsewhere in the app, and repeated purifyHtml() calls never stack
  // multiple copies of the same hook.
  DOMPurify.addHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK);
  try {
    const raw = input || '';
    // See needsForceBody()/the FORCE_BODY comment above PURIFY_CONFIG:
    // applied only when there's a real <style> tag to rescue, so every
    // other input takes the exact pre-Task-25 sanitize() call, unchanged.
    const config = needsForceBody(raw) ? { ...PURIFY_CONFIG, FORCE_BODY: true } : PURIFY_CONFIG;
    const sanitized = DOMPurify.sanitize(raw, config as any) as unknown as string;
    return scopeStyleBlocks(sanitized, raw);
  } finally {
    DOMPurify.removeHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK as any);
  }
}

export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '' }) => {
  const { connectors: { connect, drag }, selected } = useNode((node) => ({ selected: node.events.selected }));
  const clean = useMemo(() => purifyHtml(code), [code]);
  const setRef = (ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); };
  // The `style` prop is deliberately NOT applied. `toHtml()` emits only the
  // purified `code`, so anything styled here would show in the editor and
  // vanish on the live page -- the exact bug this block was reported for.
  // Wrapper styling belongs in the user's own markup (see the Edit HTML
  // toolbar's colour control). `style` stays on the props interface so
  // already-saved sites keep deserializing cleanly.
  return React.createElement('div', {
    ref: setRef,
    style: {
      minHeight: '40px',
      outline: selected ? '2px solid #3b82f6' : 'none',
    },
    dangerouslySetInnerHTML: { __html: clean },
  });
};

/* ---------- Craft config ---------- */

HtmlBlock.craft = {
  displayName: 'HTML',
  props: {
    code: '',
    style: {},
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
};

/* ---------- HTML export ---------- */

(HtmlBlock as any).toHtml = (props: HtmlBlockProps, _childrenHtml: string) => {
  // Run through the same DOMPurify config used for the live editor preview
  // so exported pages can't carry <script>/on*= payloads either.
  return { html: purifyHtml(props.code || '') };
};
