// CMW Refill page — banner & START fixed; everything else is draggable.

const CMW_PALETTES = {
  field: {
    bg: '#f6f6f6',
    banner: '#0d1f3c', bannerText: '#ffffff',
    name: '#0d1f3c',
    hero: '#3ec1ee',
    accent: '#7a1216',
    cta: '#7fd49b', ctaText: '#ffffff',
    badge: { ring: ['#e8e6df', '#b9b6ad', '#6f6c63'], center: ['#c92a2a', '#7d1414'], emblem: '#f4f1ea', stroke: '#3a1010' }
  },
  pharmacy: {
    bg: '#ffffff',
    banner: '#0e3a2a', bannerText: '#e8f5ec',
    name: '#0e3a2a',
    hero: '#2e9c5d',
    accent: '#0e3a2a',
    cta: '#c8e87a', ctaText: '#0e3a2a',
    badge: { ring: ['#f4efe2', '#cfc6b0', '#7a6f54'], center: ['#2e9c5d', '#0e3a2a'], emblem: '#fbfaf1', stroke: '#0e3a2a' }
  },
  va: {
    bg: '#f4efe2',
    banner: '#102a4f', bannerText: '#f6e7b3',
    name: '#102a4f',
    hero: '#c9a14a',
    accent: '#7a1216',
    cta: '#102a4f', ctaText: '#f6e7b3',
    badge: { ring: ['#f6e7b3', '#c9a14a', '#6b4f1c'], center: ['#7a1216', '#3a0a0c'], emblem: '#f6e7b3', stroke: '#3a0a0c' }
  }
};

const CMW_VOICES = {
  clinical: {
    greeting: 'Elaine',
    headline: 'REFILL\nAPPROVED',
    headlineCase: 'upper', headlineWeight: 900, headlineTracking: -1.5, headlineSize: 60,
    bullets: [
    "See what you're approved for.",
    "Decide if you want fewer Units",
    'Book pick-up or delivery.',
    'Pre-pay or pay at pick up.'],

    cta: 'START', ctaTracking: 2
  },
  warm: {
    greeting: 'Hey Elaine —',
    headline: 'You’re all\nset.',
    headlineCase: 'title', headlineWeight: 700, headlineTracking: -2.2, headlineSize: 56,
    bullets: [
    'Here’s what we approved this month',
    'Pick the meds that matter to you',
    'We’ll bring them, or you can swing by'],

    cta: 'Let’s go', ctaTracking: 0
  },
  urgent: {
    greeting: 'Elaine.',
    headline: 'time to\nrefill.',
    headlineCase: 'lower', headlineWeight: 800, headlineTracking: -2, headlineSize: 58,
    bullets: [
    'Approval is ready — review now',
    'Choose your meds before Friday',
    'Pick up today or schedule delivery'],

    cta: 'REFILL NOW', ctaTracking: 3
  }
};

function CMWBadge({ size = 150, palette = CMW_PALETTES.field, idSuffix = 'a' }) {
  const ringId = `ringMetal-${idSuffix}`,centerId = `centerRed-${idSuffix}`;
  const topArcId = `topArc-${idSuffix}`,botArcId = `botArc-${idSuffix}`;
  const b = palette.badge;
  return (
    <svg width={size} height={size} viewBox="0 0 200 200" style={{ display: 'block', width: "140px", height: "140px" }}>
      <defs>
        <radialGradient id={ringId} cx="50%" cy="40%" r="65%">
          <stop offset="0%" stopColor={b.ring[0]} />
          <stop offset="55%" stopColor={b.ring[1]} />
          <stop offset="100%" stopColor={b.ring[2]} />
        </radialGradient>
        <radialGradient id={centerId} cx="50%" cy="45%" r="60%">
          <stop offset="0%" stopColor={b.center[0]} />
          <stop offset="100%" stopColor={b.center[1]} />
        </radialGradient>
        <path id={topArcId} d="M 30,100 A 70,70 0 0 1 170,100" fill="none" />
        <path id={botArcId} d="M 36,108 A 64,64 0 0 0 164,108" fill="none" />
      </defs>
      <circle cx="100" cy="100" r="96" fill={`url(#${ringId})`} />
      <circle cx="100" cy="100" r="96" fill="none" stroke={b.stroke} strokeWidth="1.2" />
      <circle cx="100" cy="100" r="74" fill="none" stroke={b.stroke} strokeWidth="1.2" />
      <text fill={b.stroke} style={{ fontFamily: 'Georgia, serif', fontSize: 16, fontWeight: 700, letterSpacing: 2 }}>
        <textPath href={`#${topArcId}`} startOffset="50%" textAnchor="middle">COMBAT MEDIC</textPath>
      </text>
      <text fill={b.stroke} style={{ fontFamily: 'Georgia, serif', fontSize: 16, fontWeight: 700, letterSpacing: 4 }}>
        <textPath href={`#${botArcId}`} startOffset="50%" textAnchor="middle">WELLNESS</textPath>
      </text>
      <circle cx="100" cy="100" r="62" fill={`url(#${centerId})`} />
      <circle cx="100" cy="100" r="62" fill="none" stroke={b.stroke} strokeWidth="1" />
      {[{ x: 44 }, { x: 156 }].map((p, i) =>
      <g key={i} transform={`translate(${p.x}, 100)`}>
          <circle r="9" fill="#fff" stroke="#7a7a7a" strokeWidth="0.8" />
          <rect x="-6" y="-1.6" width="12" height="3.2" fill={b.center[0]} />
          <rect x="-1.6" y="-6" width="3.2" height="12" fill={b.center[0]} />
        </g>
      )}
      <g fill={b.emblem} stroke={b.stroke} strokeWidth="0.6">
        <g transform="translate(100,72)">
          <rect x="-9" y="-2.8" width="18" height="5.6" rx="0.5" />
          <rect x="-2.8" y="-9" width="5.6" height="18" rx="0.5" />
        </g>
        <rect x="74" y="92" width="52" height="28" rx="2" />
        <rect x="78" y="96" width="44" height="20" rx="1" fill={b.emblem} opacity="0.7" />
        <rect x="68" y="100" width="10" height="3" rx="1.5" />
        <rect x="122" y="100" width="10" height="3" rx="1.5" />
        <rect x="80" y="120" width="6" height="6" rx="1" />
        <rect x="114" y="120" width="6" height="6" rx="1" />
      </g>
    </svg>);

}

// Generic draggable wrapper.
// Drag-or-click: a small movement is treated as a click (so you can select/
// edit text in the child); movement past DRAG_THRESHOLD becomes a drag.
// While dragging, we suppress the click; otherwise it falls through naturally.
const DRAG_THRESHOLD = 4; // px

function Draggable({ x, y, w, h, onMove, children, canvasW = 393, canvasH = 852, label }) {
  const ref = React.useRef(null);
  const dragRef = React.useRef(null); // {startX,startY, dx, dy, dragging}
  const [hover, setHover] = React.useState(false);
  const [active, setActive] = React.useState(false);

  const onPointerDown = (e) => {
    // ignore right/middle clicks
    if (e.button !== 0 && e.button !== undefined) return;
    const rect = ref.current.getBoundingClientRect();
    dragRef.current = {
      startX: e.clientX, startY: e.clientY,
      dx: e.clientX - rect.left, dy: e.clientY - rect.top,
      dragging: false, pointerId: e.pointerId
    };
    // Don't capture yet — we let clicks reach the child for editing.
  };
  const onPointerMove = (e) => {
    const d = dragRef.current;
    if (!d) return;
    const movedX = e.clientX - d.startX;
    const movedY = e.clientY - d.startY;
    if (!d.dragging && Math.abs(movedX) + Math.abs(movedY) < DRAG_THRESHOLD) return;
    if (!d.dragging) {
      d.dragging = true;
      setActive(true);
      try {ref.current.setPointerCapture(d.pointerId);} catch {}
      // Cancel native text selection that may have started
      try {window.getSelection().removeAllRanges();} catch {}
    }
    e.preventDefault();
    const parent = ref.current.parentElement.getBoundingClientRect();
    const nx = e.clientX - parent.left - d.dx;
    const ny = e.clientY - parent.top - d.dy;
    onMove({
      x: Math.max(-20, Math.min(canvasW - 20, nx)),
      y: Math.max(-20, Math.min(canvasH - 20, ny))
    });
  };
  const onPointerUp = (e) => {
    const d = dragRef.current;
    dragRef.current = null;
    setActive(false);
    if (d && d.dragging) {
      try {ref.current.releasePointerCapture(d.pointerId);} catch {}
    }
  };
  // Suppress click only when we just finished dragging (prevents the
  // editor from treating an ended drag as a select).
  const onClickCapture = (e) => {
    if (active) {e.stopPropagation();e.preventDefault();}
  };

  const showOutline = hover || active;

  return (
    <div
      ref={ref}
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={onPointerUp}
      onPointerCancel={onPointerUp}
      onPointerEnter={() => setHover(true)}
      onPointerLeave={() => setHover(false)}
      onClickCapture={onClickCapture}
      title={label || 'Drag to move, click to edit'}
      style={{
        position: 'absolute', left: x, top: y,
        width: w, height: h,
        cursor: active ? 'grabbing' : 'grab',
        touchAction: 'none',
        outline: showOutline ? '1.5px dashed rgba(0,0,0,0.35)' : 'none',
        outlineOffset: 2,
        zIndex: 3
      }}>
      
      {children}
    </div>);

}

function castCase(str, mode) {
  if (mode === 'upper') return str.toUpperCase();
  if (mode === 'lower') return str.toLowerCase();
  return str;
}

function ResizableShape({ rect, onChange, color = '#ffd1e3', canvasW = 393, canvasH = 852, minW = 30, minH = 20, text, onTextChange, textStyle }) {
  const ref = React.useRef(null);
  const textRef = React.useRef(null);
  const opRef = React.useRef(null);
  const [active, setActive] = React.useState(false);
  const [hover, setHover] = React.useState(false);
  const [editing, setEditing] = React.useState(false);

  const beginMove = (e) => {
    if (editing) return;
    if (e.button !== 0 && e.button !== undefined) return;
    opRef.current = { kind: 'move', start: { x: e.clientX, y: e.clientY }, startRect: { ...rect }, dragging: false, pointerId: e.pointerId };
  };
  const beginResize = (corner) => (e) => {
    e.stopPropagation();
    if (e.button !== 0 && e.button !== undefined) return;
    opRef.current = { kind: 'resize', corner, start: { x: e.clientX, y: e.clientY }, startRect: { ...rect }, dragging: true, pointerId: e.pointerId };
    setActive(true);
    try {e.currentTarget.setPointerCapture(e.pointerId);} catch {}
  };
  const onPointerMove = (e) => {
    const op = opRef.current;
    if (!op) return;
    const dx = e.clientX - op.start.x;
    const dy = e.clientY - op.start.y;
    if (op.kind === 'move' && !op.dragging) {
      if (Math.abs(dx) + Math.abs(dy) < 4) return;
      op.dragging = true;
      setActive(true);
      try {ref.current.setPointerCapture(op.pointerId);} catch {}
    }
    e.preventDefault();
    if (op.kind === 'move') {
      onChange({ x: op.startRect.x + dx, y: op.startRect.y + dy, w: op.startRect.w, h: op.startRect.h });
    } else {
      let { x, y, w, h } = op.startRect;
      const c = op.corner;
      if (c.includes('e')) w = Math.max(minW, op.startRect.w + dx);
      if (c.includes('s')) h = Math.max(minH, op.startRect.h + dy);
      if (c.includes('w')) {const nw = Math.max(minW, op.startRect.w - dx);x = op.startRect.x + (op.startRect.w - nw);w = nw;}
      if (c.includes('n')) {const nh = Math.max(minH, op.startRect.h - dy);y = op.startRect.y + (op.startRect.h - nh);h = nh;}
      onChange({ x, y, w, h });
    }
  };
  const onPointerUp = (e) => {
    opRef.current = null;
    setActive(false);
    try {ref.current.releasePointerCapture(e.pointerId);} catch {}
  };

  const showHandles = hover || active;
  const handle = (corner, cursor, style) =>
  <div
    onPointerDown={beginResize(corner)}
    onPointerMove={onPointerMove}
    onPointerUp={onPointerUp}
    style={{ position: 'absolute', width: 14, height: 14, borderRadius: 7, background: '#fff', border: '1.5px solid rgba(0,0,0,0.55)', cursor, touchAction: 'none', zIndex: 4, opacity: showHandles ? 1 : 0, transition: 'opacity 120ms ease', ...style, padding: "0px" }} />;



  return (
    <div
      ref={ref}
      onPointerDown={beginMove}
      onPointerMove={onPointerMove}
      onPointerUp={onPointerUp}
      onPointerCancel={onPointerUp}
      onPointerEnter={() => setHover(true)}
      onPointerLeave={() => setHover(false)}
      title="Drag to move, drag corners to resize"
      style={{ position: 'absolute', left: rect.x, top: rect.y, width: rect.w, height: rect.h, background: color, boxSizing: 'border-box', border: '1px solid rgba(0,0,0,0.35)', cursor: editing ? 'text' : active ? 'grabbing' : 'grab', touchAction: 'none', outline: showHandles ? '1.5px dashed rgba(0,0,0,0.45)' : 'none', outlineOffset: 1, zIndex: 2 }}>
      
      {onTextChange &&
      <div
        ref={textRef}
        contentEditable={editing}
        suppressContentEditableWarning
        onDoubleClick={(e) => {e.stopPropagation();setEditing(true);setTimeout(() => textRef.current && textRef.current.focus(), 0);}}
        onPointerDown={(e) => {if (editing) e.stopPropagation();}}
        onBlur={(e) => {setEditing(false);onTextChange(e.currentTarget.innerText);}}
        onKeyDown={(e) => {if (e.key === 'Escape') {e.currentTarget.blur();}}}
        style={{ position: 'absolute', inset: 0, padding: 12, boxSizing: 'border-box', display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', outline: 'none', userSelect: editing ? 'text' : 'none', whiteSpace: 'pre-wrap', overflow: 'hidden', ...(textStyle || {}), color: "rgb(9, 9, 9)", fontSize: "18px" }}>
        
          {text}
        </div>
      }

      {handle('nw', 'nwse-resize', { left: -7, top: -7 })}
      {handle('ne', 'nesw-resize', { right: -7, top: -7 })}
      {handle('sw', 'nesw-resize', { left: -7, bottom: -7 })}
      {handle('se', 'nwse-resize', { right: -7, bottom: -7 })}
    </div>);

}

function CMWPage({
  paletteKey = 'field',
  voiceKey = 'clinical',
  positions,
  onMove,
  shape,
  onShapeChange,
  shapeColor = '#ffd1e3',
  textBox,
  onTextBoxChange,
  textBoxText,
  onTextBoxTextChange,
  textBoxColor = '#fff8b3'
}) {
  const p = CMW_PALETTES[paletteKey] || CMW_PALETTES.field;
  const v = CMW_VOICES[voiceKey] || CMW_VOICES.clinical;
  const move = (k) => (xy) => onMove(k, xy);

  const BANNER_H = 50;
  const CTA_H = 72;
  const BADGE_SIZE = 150;

  return (
    <div style={{ ...{
        width: '100%', height: '100%', position: 'relative',
        background: p.bg,
        fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif',
        overflow: 'hidden'
      }, background: "rgb(250, 250, 250)" }}>
      {/* FIXED banner */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: BANNER_H,
        background: p.banner, color: p.bannerText, textAlign: 'center',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '0 16px', fontSize: 16, fontWeight: 700, letterSpacing: 0.1,
        zIndex: 5
      }}>
        Questions? Call/Text 480-401-2312
      </div>

      {/* RESIZABLE pink background shape */}
      {shape && onShapeChange &&
      <ResizableShape rect={shape} onChange={onShapeChange} color={shapeColor} />
      }

      {/* RESIZABLE editable text box */}
      {textBox && onTextBoxChange &&
      <ResizableShape
        rect={textBox}
        onChange={onTextBoxChange}
        color={textBoxColor}
        text={textBoxText}
        onTextChange={onTextBoxTextChange}
        textStyle={{ fontSize: 16, fontWeight: 600, color: '#29261b', lineHeight: 1.3 }} />
      }

      {/* FIXED CTA */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, height: CTA_H,
        background: p.cta, color: p.ctaText, textAlign: 'center',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        letterSpacing: v.ctaTracking,
        zIndex: 5, fontWeight: "900", fontSize: "40px"
      }}>
        {castCase(v.cta, v.headlineCase === 'lower' ? 'lower' : v.cta === v.cta.toUpperCase() ? 'upper' : 'title')}
        <span style={{ marginLeft: 12 }}>→</span>
      </div>

      {/* DRAGGABLE: Logo image (replaces placeholder badge) */}
      <Draggable
        x={positions.badge.x} y={positions.badge.y}
        w={BADGE_SIZE} h={BADGE_SIZE}
        onMove={move('badge')} label="Drag logo">

        <img
          src="https://combatmedicwellness.com/wp-content/uploads/2024/12/logo-combat.png"
          alt="Combat Medic Wellness"
          style={{ display: 'block', width: BADGE_SIZE + 'px', height: BADGE_SIZE + 'px', objectFit: 'contain' }}
        />
      </Draggable>

      {/* DRAGGABLE: Greeting */}
      <Draggable
        x={positions.greeting.x} y={positions.greeting.y}
        w={260} h={42}
        onMove={move('greeting')} label="Drag greeting">
        
        <div style={{
          color: p.name, fontWeight: 800,
          lineHeight: 1.05, letterSpacing: -0.5, fontSize: "60px"
        }}>{v.greeting}</div>
      </Draggable>

      {/* DRAGGABLE: Headline */}
      <Draggable
        x={positions.headline.x} y={positions.headline.y}
        w={345} h={130}
        onMove={move('headline')} label="Drag headline">
        
        <div style={{ ...{
            color: p.hero, fontWeight: v.headlineWeight,
            fontSize: v.headlineSize, lineHeight: 0.98,
            letterSpacing: v.headlineTracking,
            whiteSpace: 'pre-line', textAlign: "center", width: "345px"
          }, fontSize: "55px" }}>{castCase(v.headline, v.headlineCase)}</div>
      </Draggable>

      {/* DRAGGABLE: Bullets */}
      <Draggable
        x={positions.bullets.x} y={positions.bullets.y}
        w={345} h={120}
        onMove={move('bullets')} label="Drag bullets">
        
        <ul style={{
          margin: 0, padding: 0, listStyle: 'none',
          color: p.accent, fontWeight: 700, fontSize: 17, lineHeight: 1.35
        }}>
          {v.bullets.map((t, i) =>
          <li key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '7px 0', fontSize: "24px" }}>
              <span style={{ ...{ width: 28, height: 28, borderRadius: '50%', background: p.accent, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 16, fontWeight: 800, fontFamily: 'inherit', lineHeight: 1 }, color: "rgb(232, 19, 19)", background: "rgb(248, 247, 247)" }}>{i + 1}</span>
              <span style={{ fontSize: "24px", color: "rgb(255, 255, 255)", borderStyle: "solid", borderWidth: "0px", fontFamily: "sans-serif" }}>{t}</span>
            </li>
          )}
        </ul>
      </Draggable>
    </div>);

}

Object.assign(window, { CMWPage, CMWBadge, Draggable, ResizableShape, CMW_PALETTES, CMW_VOICES });