/* global React */
// Componentes compartilhados Core 7

const C7Logo = ({ size = 40, withWordmark = true, color = "currentColor" }) => {
  // Usa a marca C7 sem fundo (PNG transparente) — perfeita sobre dark backgrounds
  return (
    <img
      src="assets/c7_mark_tight.png"
      alt="Core 7 Capital"
      style={{ display: "block", objectFit: "contain", height: "62px", width: "auto", margin: "25px 0px 0px" }} />);


};

// Ticker USDT/BRL — busca preço real da Binance (atualiza a cada 5s)
const useTicker = (base = 5.42, amplitude = 0.008) => {
  const [price, setPrice] = React.useState(base);
  const [trend, setTrend] = React.useState(0);

  React.useEffect(() => {
    let cancelled = false;

    const fetchPrice = async () => {
      try {
        const res = await fetch("https://api.binance.com/api/v3/ticker/price?symbol=USDTBRL");
        if (!res.ok) throw new Error("API error");
        const data = await res.json();
        const next = +parseFloat(data.price).toFixed(4);
        if (!cancelled && !isNaN(next)) {
          setPrice((prev) => {
            setTrend(next - prev);
            return next;
          });
        }
      } catch (e) {
        // Fallback: leve oscilação se API falhar
        if (!cancelled) {
          setPrice((prev) => {
            const drift = (Math.random() - 0.5) * amplitude * 2;
            const next = +(prev + drift).toFixed(4);
            setTrend(next - prev);
            return next;
          });
        }
      }
    };

    fetchPrice(); // primeira chamada imediata
    const id = setInterval(fetchPrice, 5000); // atualiza a cada 5s
    return () => { cancelled = true; clearInterval(id); };
  }, [amplitude]);

  return { price, trend };
};

// Hook que busca BID/ASK reais do orderbook USDT/BRL na Binance
const useOrderBook = () => {
  const [book, setBook] = React.useState({ bid: 0, ask: 0, spread: 0 });

  React.useEffect(() => {
    let cancelled = false;

    const fetchBook = async () => {
      try {
        const res = await fetch("https://api.binance.com/api/v3/ticker/bookTicker?symbol=USDTBRL");
        if (!res.ok) throw new Error("API error");
        const data = await res.json();
        const bid = parseFloat(data.bidPrice);
        const ask = parseFloat(data.askPrice);
        if (!cancelled && !isNaN(bid) && !isNaN(ask)) {
          const spread = ((ask - bid) / bid) * 100;
          setBook({ bid, ask, spread });
        }
      } catch (e) {/* mantém valores anteriores */}
    };

    fetchBook();
    const id = setInterval(fetchBook, 5000);
    return () => { cancelled = true; clearInterval(id); };
  }, []);

  return book;
};

// Sparkline animada — desenha-se ao entrar em view + cor reflete trend
const Sparkline = ({ width = 120, height = 32, color = "#9a9aa2", trend = 0 }) => {
  const [points, setPoints] = React.useState(() =>
  Array.from({ length: 24 }, () => Math.random())
  );
  const [ref, shown] = useReveal();
  const pathRef = React.useRef(null);
  const [pathLen, setPathLen] = React.useState(0);

  React.useEffect(() => {
    const id = setInterval(() => {
      setPoints((prev) => [...prev.slice(1), Math.random()]);
    }, 1200);
    return () => clearInterval(id);
  }, []);

  // Mede o comprimento real do path para a entrance (stroke-dash) animation
  React.useEffect(() => {
    if (pathRef.current && pathLen === 0) {
      try {
        setPathLen(pathRef.current.getTotalLength());
      } catch (e) {}
    }
  });

  const path = points.
  map((p, i) => {
    const x = i / (points.length - 1) * width;
    const y = height - p * height;
    return `${i === 0 ? "M" : "L"} ${x.toFixed(1)} ${y.toFixed(1)}`;
  }).
  join(" ");

  // Cor baseada no trend (verde alta, vermelho queda, neutra padrão)
  const trendColor =
  trend > 0.0005 ? "oklch(0.72 0.14 152)" :
  trend < -0.0005 ? "oklch(0.62 0.18 25)" :
  color;

  return (
    <svg ref={ref} width={width} height={height} style={{ display: "block", overflow: "visible" }}>
      <path
        ref={pathRef}
        d={path}
        fill="none"
        stroke={trendColor}
        strokeWidth="1.2"
        strokeLinecap="round"
        strokeLinejoin="round"
        opacity="0.9"
        style={{
          strokeDasharray: pathLen || "none",
          strokeDashoffset: shown ? 0 : pathLen || 1000,
          transition: "stroke-dashoffset 1.6s cubic-bezier(0.22,1,0.36,1), stroke 0.5s ease"
        }} />
      
    </svg>);

};

// Counter que conta até um número
const useCount = (target, duration = 1400) => {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(target * eased);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration]);
  return n;
};

// Hook de visibilidade (intersection)
const useReveal = () => {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      ([e]) => {if (e.isIntersecting) {setShown(true);obs.disconnect();}},
      { threshold: 0.15 }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return [ref, shown];
};

// Reveal wrapper
const Reveal = ({ children, delay = 0, y = 24, style = {}, ...rest }) => {
  const [ref, shown] = useReveal();
  return (
    <div
      ref={ref}
      style={{
        opacity: shown ? 1 : 0,
        transform: shown ? "translateY(0)" : `translateY(${y}px)`,
        transition: `opacity 0.9s cubic-bezier(.2,.7,.2,1) ${delay}ms, transform 0.9s cubic-bezier(.2,.7,.2,1) ${delay}ms`,
        ...style
      }}
      {...rest}>
      
      {children}
    </div>);

};

// Hairline animada
const Hairline = ({ vertical = false, length = "100%", color = "rgba(255,255,255,0.16)" }) =>
<div
  style={{
    [vertical ? "width" : "height"]: 1,
    [vertical ? "height" : "width"]: length,
    background: vertical ?
    `linear-gradient(180deg, transparent, ${color}, transparent)` :
    `linear-gradient(90deg, transparent, ${color}, transparent)`
  }} />;



// Botão padrão
const C7Button = ({ children, variant = "primary", icon, onClick, style = {}, as = "button", href }) => {
  const base = {
    display: "inline-flex",
    alignItems: "center",
    gap: 10,
    padding: "14px 22px",
    fontFamily: "var(--c7-font-display)",
    fontSize: 13,
    fontWeight: 500,
    letterSpacing: "0.16em",
    textTransform: "uppercase",
    borderRadius: 2,
    transition: "all 0.3s ease",
    cursor: "pointer",
    border: "1px solid",
    whiteSpace: "nowrap"
  };
  const variants = {
    primary: {
      background: "linear-gradient(180deg, #e6e6ea 0%, #c8c8cd 100%)",
      color: "#0b0b0d",
      borderColor: "#c8c8cd"
    },
    ghost: {
      background: "transparent",
      color: "var(--c7-platinum)",
      borderColor: "rgba(255,255,255,0.2)"
    },
    accent: {
      background: "transparent",
      color: "var(--c7-platinum)",
      borderColor: "var(--c7-accent)"
    }
  };
  const Comp = as;
  return (
    <Comp
      href={href}
      onClick={onClick}
      style={{ ...base, ...variants[variant], ...style }}
      onMouseEnter={(e) => {
        if (variant === "ghost") e.currentTarget.style.borderColor = "rgba(255,255,255,0.5)";
        if (variant === "primary") e.currentTarget.style.transform = "translateY(-1px)";
        if (variant === "accent") e.currentTarget.style.background = "rgba(220,80,60,0.08)";
      }}
      onMouseLeave={(e) => {
        if (variant === "ghost") e.currentTarget.style.borderColor = "rgba(255,255,255,0.2)";
        if (variant === "primary") e.currentTarget.style.transform = "translateY(0)";
        if (variant === "accent") e.currentTarget.style.background = "transparent";
      }}>
      
      {children}
      {icon && <span style={{ fontSize: 14 }}>{icon}</span>}
    </Comp>);

};

// Quote calculator (mesa OTC)
const QuoteCalculator = ({ t, accent = "#c8c8cd", onConfirm }) => {
  const [side, setSide] = React.useState("buy");
  const [amount, setAmount] = React.useState(100000);
  const { price: mid } = useTicker(5.42, 0.005);
  const spreadPct = side === "buy" ? 0.0048 : 0.0042;
  const c7Rate = side === "buy" ?
  mid * (1 + spreadPct) :
  mid * (1 - spreadPct);
  const receive = side === "buy" ? amount / c7Rate : amount * c7Rate;
  const fmt = (n, d = 2) => n.toLocaleString("pt-BR", { minimumFractionDigits: d, maximumFractionDigits: d });

  // Mínimo operacional: R$ 500 — tanto para pagar (comprar) quanto para receber (vender)
  const MIN_BRL = 500;
  const brlValue = side === "buy" ? amount : receive;
  const belowMin = brlValue < MIN_BRL;
  return (
    <div style={{
      background: "rgba(20,20,26,0.6)",
      border: "1px solid rgba(255,255,255,0.10)",
      backdropFilter: "blur(12px)",
      padding: 28,
      borderRadius: 4
    }}>
      {/* Tabs */}
      <div style={{ display: "flex", gap: 0, marginBottom: 24, borderBottom: "1px solid rgba(255,255,255,0.08)" }}>
        {[
        { k: "buy", l: t.side_buy },
        { k: "sell", l: t.side_sell }].
        map((o) =>
        <button
          key={o.k}
          onClick={() => setSide(o.k)}
          style={{
            flex: 1,
            padding: "14px 16px",
            fontFamily: "var(--c7-font-mono)",
            fontSize: 11,
            letterSpacing: "0.18em",
            textTransform: "uppercase",
            color: side === o.k ? "var(--c7-platinum)" : "var(--c7-silver-1)",
            borderBottom: `2px solid ${side === o.k ? accent : "transparent"}`,
            transition: "all 0.3s"
          }}>
          
            {o.l}
          </button>
        )}
      </div>

      {/* Volume */}
      <div style={{ marginBottom: 20 }}>
        <label style={{ display: "block", fontFamily: "var(--c7-font-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--c7-silver-1)", textTransform: "uppercase", marginBottom: 8 }}>
          {t.amount} ({side === "buy" ? "BRL" : "USDT"})
        </label>
        <div style={{ position: "relative" }}>
          <input
            type="number"
            value={amount}
            onChange={(e) => setAmount(+e.target.value || 0)}
            style={{
              width: "100%",
              background: "rgba(0,0,0,0.4)",
              border: "1px solid rgba(255,255,255,0.10)",
              padding: "16px 18px",
              fontFamily: "var(--c7-font-display)",
              fontSize: 22,
              color: "var(--c7-white)",
              borderRadius: 2,
              outline: "none",
              fontWeight: 500
            }} />
          
          <span style={{
            position: "absolute",
            right: 18,
            top: "50%",
            transform: "translateY(-50%)",
            fontFamily: "var(--c7-font-mono)",
            fontSize: 11,
            color: "var(--c7-silver-1)",
            letterSpacing: "0.15em"
          }}>
            {side === "buy" ? "BRL" : "USDT"}
          </span>
        </div>
      </div>

      {/* Você recebe */}
      <div style={{ marginBottom: 20 }}>
        <label style={{ display: "block", fontFamily: "var(--c7-font-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--c7-silver-1)", textTransform: "uppercase", marginBottom: 8 }}>
          {t.receive}*
        </label>
        <div style={{
          background: "rgba(0,0,0,0.4)",
          border: "1px solid rgba(255,255,255,0.10)",
          padding: "16px 18px",
          fontFamily: "var(--c7-font-display)",
          fontSize: 28,
          color: "var(--c7-white)",
          fontWeight: 500,
          borderRadius: 2,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center"
        }}>
          <span>{fmt(receive, side === "buy" ? 4 : 2)}</span>
          <span style={{ fontFamily: "var(--c7-font-mono)", fontSize: 12, color: "var(--c7-silver-1)" }}>
            {side === "buy" ? "USDT" : "BRL"}
          </span>
        </div>
      </div>

      {/* Detalhes */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gap: 1,
        background: "rgba(255,255,255,0.06)",
        marginBottom: 24
      }}>
        <div style={{ background: "rgba(20,20,26,0.9)", padding: "12px 14px" }}>
          <div style={{ fontFamily: "var(--c7-font-mono)", fontSize: 9, color: "var(--c7-silver-1)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 4 }}>{t.rate}</div>
          <div style={{ fontFamily: "var(--c7-font-mono)", fontSize: 14, color: "var(--c7-platinum)" }}>R$ {fmt(c7Rate, 4)}</div>
        </div>
        <div style={{ background: "rgba(20,20,26,0.9)", padding: "12px 14px" }}>
          <div style={{ fontFamily: "var(--c7-font-mono)", fontSize: 9, color: "var(--c7-silver-1)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 4 }}>{t.mid}</div>
          <div style={{ fontFamily: "var(--c7-font-mono)", fontSize: 14, color: "var(--c7-silver-2)" }}>R$ {fmt(mid, 4)}</div>
        </div>
        <div style={{ background: "rgba(20,20,26,0.9)", padding: "12px 14px" }}>
          <div style={{ fontFamily: "var(--c7-font-mono)", fontSize: 9, color: "var(--c7-silver-1)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 4 }}>{t.spread}</div>
          <div style={{ fontFamily: "var(--c7-font-mono)", fontSize: 14, color: "var(--c7-platinum)" }}>{(spreadPct * 100).toFixed(2)}%</div>
        </div>
        <div style={{ background: "rgba(20,20,26,0.9)", padding: "12px 14px" }}>
          <div style={{ fontFamily: "var(--c7-font-mono)", fontSize: 9, color: "var(--c7-silver-1)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 4 }}>{t.settle}</div>
          <div style={{ fontFamily: "var(--c7-font-mono)", fontSize: 14, color: "var(--c7-platinum)" }}>~ 4 min</div>
        </div>
      </div>

      {/* Aviso de valor mínimo */}
      {belowMin && (
        <div style={{
          marginBottom: 14,
          padding: "10px 14px",
          background: "rgba(220,80,60,0.08)",
          border: "1px solid rgba(220,80,60,0.35)",
          borderRadius: 2,
          fontFamily: "var(--c7-font-mono)",
          fontSize: 10,
          color: "var(--c7-platinum)",
          letterSpacing: "0.08em",
          lineHeight: 1.5
        }}>
          {t.side_buy && t.side_buy.startsWith("Buy")
            ? (side === "buy"
                ? "Minimum amount to send: R$ 500.00"
                : "Minimum amount to receive: R$ 500.00")
            : (side === "buy"
                ? "Valor mínimo a enviar: R$ 500,00"
                : "Valor mínimo a receber: R$ 500,00")}
        </div>
      )}

      <C7Button
        variant="primary"
        onClick={belowMin ? undefined : () => onConfirm({ side, amount, receive, c7Rate, mid, spreadPct })}
        style={{
          width: "100%",
          justifyContent: "center",
          opacity: belowMin ? 0.4 : 1,
          cursor: belowMin ? "not-allowed" : "pointer",
          pointerEvents: belowMin ? "none" : "auto"
        }}>
        {t.cta} →
      </C7Button>

      <div style={{ marginTop: 14, fontFamily: "var(--c7-font-mono)", fontSize: 10, color: "var(--c7-silver-1)", letterSpacing: "0.05em", lineHeight: 1.5 }}>
        * {t.disclaimer}
      </div>
    </div>);

};

Object.assign(window, {
  C7Logo, useTicker, Sparkline, useCount, useReveal, Reveal, Hairline, C7Button, QuoteCalculator
});