/* ============================================================
   bezikaron — общие UI-компоненты и иконки.
   Иконки: тонкая линия, спокойные, без агрессии.
   ============================================================ */

// ---------- Иконки (line, currentColor) ----------
function Icon({ name, size = 24, stroke = 1.6, style = {} }) {
  const p = { fill: 'none', stroke: 'currentColor', strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const paths = {
    leaf: <><path {...p} d="M5 19c0-7 5-12 14-13 0 9-5 14-13 14-1 0-1-1-1-1Z"/><path {...p} d="M8 17c3-4 6-6 9-7"/></>,
    home: <><path {...p} d="M4 11.5l8-7 8 7"/><path {...p} d="M6.2 10v9.2h11.6V10"/><path {...p} d="M10 19.2v-5.2h4v5.2"/></>,
    sparkle: <><path {...p} d="M12 3l1.6 5.4L19 10l-5.4 1.6L12 17l-1.6-5.4L5 10l5.4-1.6Z"/><path {...p} d="M18 15l.7 2.3L21 18l-2.3.7L18 21l-.7-2.3L15 18l2.3-.7Z"/></>,
    text: <><path {...p} d="M6 6h12M9 6v12M15 6v12"/></>,
    level: <><path {...p} d="M4 14h16M4 14l3-7h10l3 7M9 14v4M15 14v4"/></>,
    camera: <><rect {...p} x="3" y="7" width="18" height="13" rx="3"/><path {...p} d="M9 7l1.5-2.5h3L15 7"/><circle {...p} cx="12" cy="13.5" r="3.3"/></>,
    pin: <><path {...p} d="M12 21s-6.5-5.6-6.5-10.5A6.5 6.5 0 0 1 18.5 10.5C18.5 15.4 12 21 12 21Z"/><circle {...p} cx="12" cy="10.5" r="2.4"/></>,
    shield: <><path {...p} d="M12 3l7 3v5c0 5-3.5 8.5-7 10-3.5-1.5-7-5-7-10V6Z"/><path {...p} d="M9 11.5l2 2 4-4.5"/></>,
    lock: <><rect {...p} x="5" y="10.5" width="14" height="9.5" rx="2.2"/><path {...p} d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/></>,
    doc: <><path {...p} d="M7 3h7l4 4v14H7Z"/><path {...p} d="M14 3v4h4M10 13h6M10 17h4"/></>,
    phone: <><path {...p} d="M6 4h3l1.5 4-2 1.5a11 11 0 0 0 5 5l1.5-2 4 1.5V18a2 2 0 0 1-2 2A14 14 0 0 1 4 6 2 2 0 0 1 6 4Z"/></>,
    mail: <><rect {...p} x="3" y="5" width="18" height="14" rx="2.5"/><path {...p} d="M4 7l8 6 8-6"/></>,
    chat: <><path {...p} d="M4 6.5A2.5 2.5 0 0 1 6.5 4h11A2.5 2.5 0 0 1 20 6.5v7A2.5 2.5 0 0 1 17.5 16H9l-4 4Z"/></>,
    check: <><path {...p} d="M5 12.5l4.5 4.5L19 7"/></>,
    arrow: <><path {...p} d="M5 12h14M13 6l6 6-6 6"/></>,
    arrowL: <><path {...p} d="M19 12H5M11 6l-6 6 6 6"/></>,
    search: <><circle {...p} cx="11" cy="11" r="6.5"/><path {...p} d="M20 20l-3.8-3.8"/></>,
    upload: <><path {...p} d="M12 16V4M8 8l4-4 4 4"/><path {...p} d="M5 16v2a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-2"/></>,
    help: <><circle {...p} cx="12" cy="12" r="9"/><path {...p} d="M9.5 9.5a2.5 2.5 0 0 1 4.8.9c0 1.7-2.3 2.1-2.3 3.6"/><circle cx="12" cy="17" r="0.9" fill="currentColor" stroke="none"/></>,
    calendar: <><rect {...p} x="4" y="5" width="16" height="16" rx="2.5"/><path {...p} d="M4 9h16M8 3v4M16 3v4"/></>,
    heart: <><path {...p} d="M12 20s-7-4.5-7-10a4 4 0 0 1 7-2.5A4 4 0 0 1 19 10c0 5.5-7 10-7 10Z"/></>,
    clock: <><circle {...p} cx="12" cy="12" r="8.5"/><path {...p} d="M12 7.5V12l3 2"/></>,
    user: <><circle {...p} cx="12" cy="8.5" r="3.7"/><path {...p} d="M5.5 19.5a6.5 6.5 0 0 1 13 0"/></>,
    apple: <><path {...p} d="M15.8 4.2c.2 1-.2 1.9-.8 2.6-.6.7-1.6 1.2-2.5 1.1-.2-1 .3-2 .9-2.6.6-.7 1.7-1.2 2.4-1.1ZM18.5 16.6c-.4 1-.6 1.4-1.1 2.3-.7 1.2-1.7 2.7-2.9 2.7-1.1 0-1.4-.7-2.9-.7-1.5 0-1.8.7-2.9.7-1.2 0-2.1-1.3-2.8-2.5-2-3.1-2.2-6.8-1-8.8.9-1.4 2.2-2.2 3.5-2.2 1.3 0 2.1.7 3.2.7 1 0 1.7-.7 3.2-.7 1.1 0 2.3.6 3.2 1.7-2.8 1.5-2.3 5.4.2 6.8Z"/></>,
    play: <><path {...p} d="M5 3.5v17l13-8.5z"/></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={style} aria-hidden="true">
      {paths[name] || null}
    </svg>
  );
}

// иконка по id услуги
const SERVICE_ICON = { clean: 'sparkle', letters: 'text', plot: 'leaf', level: 'level' };

// ---------- Секция ----------
function Section({ children, tint = false, style = {}, id, reveal = true }) {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    if (!reveal) { setShown(true); return; }
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { setShown(true); return; }
    // корень наблюдателя — ближайший прокручиваемый предок (внутри телефона)
    let root = el.parentElement;
    while (root) {
      const oy = getComputedStyle(root).overflowY;
      if (oy === 'auto' || oy === 'scroll') break;
      root = root.parentElement;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setShown(true); io.disconnect(); } });
    }, { root: root || null, rootMargin: '0px 0px -6% 0px', threshold: 0.06 });
    io.observe(el);
    return () => io.disconnect();
  }, [reveal]);
  return (
    <section ref={ref} id={id} className={reveal ? (shown ? 'reveal in' : 'reveal') : undefined} style={{
      padding: '38px 22px',
      background: tint ? 'var(--surface-2)' : 'transparent',
      ...style,
    }}>
      {children}
    </section>
  );
}

function Eyebrow({ children }) {
  return <div className="t-eyebrow" style={{ marginBottom: 12 }}>{children}</div>;
}

// ---------- Кружок-иконка ----------
function IconDisc({ name, tone = 'accent', size = 46 }) {
  const tones = {
    accent: { bg: 'var(--accent-tint)', fg: 'var(--accent-deep)' },
    bronze: { bg: 'var(--bronze-tint)', fg: 'var(--bronze-deep)' },
  };
  const t = tones[tone] || tones.accent;
  return (
    <div style={{
      width: size, height: size, borderRadius: 14, flexShrink: 0,
      background: t.bg, color: t.fg,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <Icon name={name} size={Math.round(size * 0.52)} />
    </div>
  );
}

// ---------- Метка-заглушка ----------
function PlaceholderTag({ children = 'ממלא מקום' }) {
  return (
    <span className="placeholder-tag">
      <span style={{ width: 5, height: 5, borderRadius: 999, background: 'currentColor', display: 'inline-block' }} />
      {children}
    </span>
  );
}

// ---------- Слайдер «до / после» ----------
function BeforeAfter({ pairs = [] }) {
  const [idx, setIdx] = React.useState(0);
  const [pos, setPos] = React.useState(50);
  const [touched, setTouched] = React.useState(false);
  const ref = React.useRef(null);
  const dragging = React.useRef(false);
  const cur = pairs[idx] || {};

  const move = (clientX) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    let pct = ((clientX - r.left) / r.width) * 100;
    pct = Math.max(2, Math.min(98, pct));
    setPos(pct);
  };
  React.useEffect(() => {
    const up = () => { dragging.current = false; };
    const mv = (e) => { if (dragging.current) move(e.touches ? e.touches[0].clientX : e.clientX); };
    window.addEventListener('mousemove', mv); window.addEventListener('mouseup', up);
    window.addEventListener('touchmove', mv, { passive: true }); window.addEventListener('touchend', up);
    return () => {
      window.removeEventListener('mousemove', mv); window.removeEventListener('mouseup', up);
      window.removeEventListener('touchmove', mv); window.removeEventListener('touchend', up);
    };
  }, []);

  const imgStyle = {
    position: 'absolute', inset: 0, width: '100%', height: '100%',
    objectFit: 'cover', objectPosition: 'center 38%', userSelect: 'none', pointerEvents: 'none',
  };

  return (
    <div>
      <div ref={ref} style={{
        position: 'relative', height: 320, borderRadius: 'var(--r-lg)',
        overflow: 'hidden', border: '1px solid var(--line)', cursor: 'ew-resize',
        userSelect: 'none', boxShadow: 'var(--shadow-card)', background: 'var(--surface-2)',
      }}
        onMouseDown={(e) => { dragging.current = true; setTouched(true); move(e.clientX); }}
        onTouchStart={(e) => { dragging.current = true; setTouched(true); move(e.touches[0].clientX); }}
      >
        {/* после — целиком */}
        <img src={cur.after} alt="אחרי" draggable={false} style={imgStyle} />
        {/* до — поверх, обрезано по позиции ручки */}
        <img src={cur.before} alt="לפני" draggable={false} style={{ ...imgStyle, clipPath: `inset(0 ${100 - pos}% 0 0)` }} />
        {/* подписи углов */}
        <span style={cornerTag(true)}>לפני</span>
        <span style={cornerTag(false)}>אחרי</span>
        {/* ручка */}
        <div style={{ position: 'absolute', top: 0, bottom: 0, left: `${pos}%`, width: 2, background: 'rgba(251,250,246,0.95)', transform: 'translateX(-1px)', boxShadow: '0 0 6px rgba(0,0,0,0.25)' }} />
        {/* мягкая подсказка «потяните» — гаснет после первого касания */}
        {!touched && (
          <span className="ba-pulse" style={{
            position: 'absolute', top: '50%', left: `${pos}%`, transform: 'translate(-50%,-50%)',
            width: 42, height: 42, borderRadius: 999, pointerEvents: 'none',
          }} />
        )}
        <div style={{
          position: 'absolute', top: '50%', left: `${pos}%`, transform: 'translate(-50%,-50%)',
          width: 42, height: 42, borderRadius: 999, background: 'var(--surface)',
          boxShadow: 'var(--shadow-pop)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--ink-soft)', gap: 2,
        }}>
          <Icon name="arrowL" size={15} /><Icon name="arrow" size={15} />
        </div>
      </div>

      {/* выбор примера */}
      {pairs.length > 1 && (
        <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
          {pairs.map((p, i) => {
            const on = i === idx;
            return (
              <button key={p.id} onClick={() => { setIdx(i); setPos(50); }} style={{
                flex: 1, cursor: 'pointer', padding: 0, borderRadius: 'var(--r-sm)', overflow: 'hidden',
                border: on ? '2px solid var(--accent)' : '1.5px solid var(--line)',
                background: 'var(--surface-2)', position: 'relative', height: 60,
                boxShadow: on ? '0 4px 14px color-mix(in oklch, var(--accent) 22%, transparent)' : 'var(--shadow-soft)',
                transition: 'all .15s ease', WebkitTapHighlightColor: 'transparent',
              }}>
                <img src={p.after} alt={p.label} draggable={false} style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 40%', opacity: on ? 1 : 0.78 }} />
                <span style={{
                  position: 'absolute', insetInline: 0, bottom: 0, padding: '7px 6px 5px',
                  fontSize: 11.5, fontWeight: 700, color: '#FBFAF6', textAlign: 'center',
                  background: 'linear-gradient(to top, rgba(20,20,18,0.66), transparent)',
                }}>{p.label}</span>
              </button>
            );
          })}
        </div>
      )}
      <p className="t-small" style={{ marginTop: 12 }}>עבודות אמיתיות של הצוות שלנו. גררו את המחוון כדי להשוות.</p>
    </div>
  );
}
function cornerTag(left) {
  return {
    position: 'absolute', top: 12, [left ? 'left' : 'right']: 12,
    fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
    color: 'var(--ink)', background: 'rgba(251,250,246,0.82)',
    backdropFilter: 'blur(4px)', padding: '5px 10px', borderRadius: 999,
  };
}

// ---------- Список с галочками ----------
function CheckList({ items, tone = 'accent' }) {
  return (
    <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 11 }}>
      {items.map((it, i) => (
        <li key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 11 }}>
          <span style={{
            width: 22, height: 22, borderRadius: 999, flexShrink: 0, marginTop: 1,
            background: tone === 'bronze' ? 'var(--bronze-tint)' : 'var(--accent-tint)',
            color: tone === 'bronze' ? 'var(--bronze-deep)' : 'var(--accent-deep)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name="check" size={14} stroke={2} /></span>
          <span className="t-body">{it}</span>
        </li>
      ))}
    </ul>
  );
}

Object.assign(window, {
  Icon, SERVICE_ICON, Section, Eyebrow, IconDisc, PlaceholderTag, BeforeAfter, CheckList,
});
