// Brand panel — left side. Holds logo, headline, trust signals, testimonial
// carousel, partner-logo row, and live "your answers" chips that appear as the
// user progresses through the form.

const TESTIMONIALS = [
  {
    quote: "They reviewed my contract within 48 hours and flagged terms I never would have caught. Saved my business.",
    name: "Marcus T.",
    role: "Restaurant Owner, Tampa FL",
    source: "Google",
  },
  {
    quote: "Three stacked advances, two COJs, sleepless nights. After their review I had a plan in writing the same week.",
    name: "Diane R.",
    role: "Trucking Co., Dallas TX",
    source: "Trustpilot",
  },
  {
    quote: "Honest advisors. They didn't oversell — told me upfront which advances were negotiable and which weren't.",
    name: "Antonio V.",
    role: "HVAC Contractor, Phoenix AZ",
    source: "Google",
  },
];

function DiamondMark({ size = 28, color = "#F6F1E5" }) {
  // Cluster of 5 small diamonds in a quincunx — matches the reference logo's geometric mark.
  const s = size;
  const d = s * 0.22;
  const c = s / 2;
  const positions = [
    { x: c, y: d * 0.7 },           // top
    { x: d * 0.7, y: c },           // left
    { x: c, y: c },                 // center
    { x: s - d * 0.7, y: c },       // right
    { x: c, y: s - d * 0.7 },       // bottom
  ];
  return (
    <svg width={s} height={s} viewBox={`0 0 ${s} ${s}`} aria-hidden="true">
      {positions.map((p, i) => (
        <rect
          key={i}
          x={-d / 2} y={-d / 2}
          width={d} height={d}
          fill={color}
          transform={`translate(${p.x} ${p.y}) rotate(45)`}
        />
      ))}
    </svg>
  );
}

function Stars({ value = 5, green = false }) {
  const full = Math.floor(value);
  const half = value - full >= 0.5;
  return (
    <div className={`stars${green ? " green" : ""}`} aria-label={`${value} of 5 stars`}>
      {Array.from({ length: 5 }).map((_, i) => {
        const filled = i < full;
        const isHalf = !filled && i === full && half;
        return (
          <svg key={i} width="13" height="13" viewBox="0 0 24 24" aria-hidden="true">
            <defs>
              <linearGradient id={`h${i}`}>
                <stop offset="50%" stopColor="currentColor" />
                <stop offset="50%" stopColor="currentColor" stopOpacity="0.25" />
              </linearGradient>
            </defs>
            <path
              d="M12 2 14.9 8.6 22 9.3 16.7 14 18.3 21 12 17.3 5.7 21 7.3 14 2 9.3 9.1 8.6Z"
              fill={filled ? "currentColor" : isHalf ? `url(#h${i})` : "currentColor"}
              opacity={filled || isHalf ? 1 : 0.22}
            />
          </svg>
        );
      })}
    </div>
  );
}

function ReviewsCarousel() {
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setIdx((i) => (i + 1) % TESTIMONIALS.length), 6000);
    return () => clearInterval(t);
  }, []);
  const t = TESTIMONIALS[idx];
  return (
    <div className="reviews">
      <div className="review-row three">
        <div className="review-cell">
          <Stars value={4.9} />
          <div className="rating">4.9</div>
          <div className="rating-label">Google · 312 reviews</div>
        </div>
        <div className="review-cell">
          <Stars value={4.8} green />
          <div className="rating">4.8</div>
          <div className="rating-label">Trustpilot · 187 reviews</div>
        </div>
        <div className="review-cell">
          <div className="bbb-letter" aria-hidden="true">A</div>
          <div className="rating">A</div>
          <div className="rating-label">BBB rating</div>
        </div>
      </div>
      <p className="quote" key={idx}>{t.quote}</p>
      <div className="attrib">
        <span>{t.name}, {t.role}</span>
        <span className="dot">·</span>
        <span>via {t.source}</span>
      </div>
      <div className="review-dots">
        {TESTIMONIALS.map((_, i) => <i key={i} className={i === idx ? "on" : ""} />)}
      </div>
    </div>
  );
}

function SocialLinks({ variant }) {
  // Outbound "see what people say" links — opens in a new tab in production.
  const items = [
    {
      label: "Google",
      sub: "Reviews",
      href: "https://share.google/KYJpIuNbLbEOA2FA3",
      icon: (
        <svg width="14" height="14" viewBox="0 0 24 24" aria-hidden="true">
          <path fill="#4285F4" d="M23.5 12.27c0-.79-.07-1.55-.2-2.27H12v4.51h6.47c-.28 1.4-1.07 2.6-2.28 3.42v2.84h3.67C21.97 18.7 23.5 15.74 23.5 12.27z"/>
          <path fill="#34A853" d="M12 24c3.08 0 5.66-1.02 7.55-2.77l-3.67-2.84c-1.02.68-2.32 1.07-3.88 1.07-2.98 0-5.5-2.01-6.4-4.72H1.81v2.93C3.7 21.39 7.55 24 12 24z"/>
          <path fill="#FBBC05" d="M5.6 14.74c-.23-.68-.36-1.4-.36-2.14s.13-1.46.36-2.14V7.53H1.81C1.07 9.04.64 10.74.64 12.6s.43 3.56 1.17 5.07L5.6 14.74z"/>
          <path fill="#EA4335" d="M12 4.75c1.68 0 3.18.58 4.36 1.71l3.27-3.27C17.66 1.19 15.08 0 12 0 7.55 0 3.7 2.61 1.81 6.53l3.79 2.93C6.5 6.76 9.02 4.75 12 4.75z"/>
        </svg>
      ),
    },
    {
      label: "Trustpilot",
      sub: "Reviews",
      href: "https://www.trustpilot.com/review/businessdebtadjusters.com",
      icon: (
        <svg width="14" height="14" viewBox="0 0 24 24" aria-hidden="true">
          <polygon points="12,2 14.9,8.6 22,9.3 16.7,14 18.3,21 12,17.3 5.7,21 7.3,14 2,9.3 9.1,8.6" fill="#00B67A"/>
        </svg>
      ),
    },
    {
      label: "BBB",
      sub: "A rated",
      href: "https://www.bbb.org/us/nj/englewd-clfs/profile/debt-relief-services/business-debt-adjusters-0221-90179879",
      icon: (
        <svg width="20" height="14" viewBox="0 0 28 14" aria-hidden="true">
          <rect x="0" y="0" width="28" height="14" rx="2" fill="#4A86C9"/>
          <text x="14" y="10" fontFamily="ui-sans-serif, system-ui, sans-serif" fontSize="8" fontWeight="700" fill="#fff" textAnchor="middle" letterSpacing="0.5">BBB</text>
        </svg>
      ),
    },
    {
      label: "Instagram",
      sub: "@bdadjusters",
      href: "https://www.instagram.com/",
      icon: (
        <svg width="14" height="14" viewBox="0 0 24 24" aria-hidden="true">
          <defs>
            <linearGradient id="igGrad" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0%" stopColor="#F58529"/>
              <stop offset="50%" stopColor="#DD2A7B"/>
              <stop offset="100%" stopColor="#8134AF"/>
            </linearGradient>
          </defs>
          <rect x="3" y="3" width="18" height="18" rx="5" fill="url(#igGrad)"/>
          <circle cx="12" cy="12" r="4" fill="none" stroke="#fff" strokeWidth="1.6"/>
          <circle cx="17.5" cy="6.5" r="1.1" fill="#fff"/>
        </svg>
      ),
    },
    {
      label: "Blog",
      sub: "Insights",
      href: "https://www.businessdebtadjusters.com/blog",
      icon: (
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
             strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M4 4h11l5 5v11a0 0 0 0 1 0 0H4z"/>
          <path d="M15 4v5h5"/>
          <path d="M8 13h7M8 17h5"/>
        </svg>
      ),
    },
  ];
  return (
    <div className={variant === "thanks" ? "social-links thanks-variant" : "social-links"}>
      {variant !== "thanks" && <div className="social-links-label">See what people say</div>}
      <div className="social-links-row">
        {items.map((it) => (
          <a key={it.label} href={it.href} target="_blank" rel="noopener" className="social-link">
            <span className="social-icon">{it.icon}</span>
            <span className="social-meta">
              <span className="social-label">{it.label}</span>
              <span className="social-sub">{it.sub}</span>
            </span>
            <svg className="social-arrow" width="11" height="11" viewBox="0 0 24 24" fill="none"
                 stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
                 aria-hidden="true">
              <path d="M7 17L17 7M9 7h8v8" />
            </svg>
          </a>
        ))}
      </div>
    </div>
  );
}

function PromisesBlock() {
  // Reassurance / sales copy that sits between the live answer chips and the
  // testimonial carousel. Keeps the brand panel earning its space while users
  // are on the form, and reinforces the no-pressure positioning.
  const items = [
    { label: "No upfront fees", sub: "Performance-based. You pay only on results." },
    { label: "No high-pressure sales", sub: "One advisor, one call, no scripts. You decide." },
    { label: "Confidential review", sub: "Encrypted intake. Nothing shared with funders." },
    { label: "Hardship program", sub: "Immediate payment relief while your case is reviewed." },
  ];
  return (
    <div className="promises">
      <div className="promises-label">What you can expect</div>
      <ul className="promises-list">
        {items.map((it) => (
          <li key={it.label}>
            <span className="promises-mark" aria-hidden="true">
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 13l4 4L19 7" />
              </svg>
            </span>
            <span className="promises-body">
              <span className="promises-text">{it.label}</span>
              <span className="promises-sub">{it.sub}</span>
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}

const UGC_CLIPS = [
  // Real CDN clips. Names derived from filenames; tweak the `role` copy as
  // you confirm each customer's actual business.
  { name: "Ashutos Barua",    role: "Small business owner",       src: "https://assets.businessdebtadjusters.net/videos/ashutos-barua.mp4",    hue: 200 },
  { name: "Clifford Apter",   role: "Small business owner",       src: "https://assets.businessdebtadjusters.net/videos/clifford-apter.mp4",   hue: 24  },
  { name: "Darryl Parraway",  role: "Small business owner",       src: "https://assets.businessdebtadjusters.net/videos/darryl-parraway-1.mp4", hue: 280 },
  { name: "David Kocemba",    role: "Small business owner",       src: "https://assets.businessdebtadjusters.net/videos/david-kocemba.mp4",    hue: 12  },
  // Fallback for thank-you page
  { name: "Davis Williams",   role: "Small business owner",       src: "https://assets.businessdebtadjusters.net/videos/davis-williams.mp4",   hue: 320 },
];

// Full library for the thank-you "Stories from owners we've helped" rail.
const UGC_LIBRARY = [
  { name: "Ashutos Barua",   src: "https://assets.businessdebtadjusters.net/videos/ashutos-barua.mp4" },
  { name: "Clifford Apter",  src: "https://assets.businessdebtadjusters.net/videos/clifford-apter.mp4" },
  { name: "Darryl Parraway", src: "https://assets.businessdebtadjusters.net/videos/darryl-parraway-1.mp4" },
  { name: "Darryl Parraway", src: "https://assets.businessdebtadjusters.net/videos/darryl-parraway-2.mp4" },
  { name: "David Kocemba",   src: "https://assets.businessdebtadjusters.net/videos/david-kocemba.mp4" },
  { name: "Davis Williams",  src: "https://assets.businessdebtadjusters.net/videos/davis-williams.mp4" },
  { name: "Jeffrey Dumlao",  src: "https://assets.businessdebtadjusters.net/videos/jeffrey-dumlao.mp4" },
  { name: "Jeffrey Landis",  src: "https://assets.businessdebtadjusters.net/videos/jeffrey-landis.mp4" },
  { name: "Joseph Lee",      src: "https://assets.businessdebtadjusters.net/videos/joseph-lee.mp4" },
  { name: "Keith Dugan",     src: "https://assets.businessdebtadjusters.net/videos/keith-dugan.mp4" },
  { name: "Millie Wright",   src: "https://assets.businessdebtadjusters.net/videos/millie-wright.mp4" },
  { name: "Mohan Ramisetty", src: "https://assets.businessdebtadjusters.net/videos/mohan-ramisetty.mp4" },
  { name: "Schuyler Judd",   src: "https://assets.businessdebtadjusters.net/videos/schuyler-judd.mp4" },
  { name: "Steven Pearish",  src: "https://assets.businessdebtadjusters.net/videos/steven-pearish.mp4" },
  { name: "Treka Bozzato",   src: "https://assets.businessdebtadjusters.net/videos/treka-bozzato.mp4" },
];

function UgcVideo({ stepIdx = 0, submitted = false }) {
  // Single looping reel — once you cut a reel from the library, drop its CDN
  // URL into REEL_SRC and this slot plays it on loop.
  const REEL_SRC = "https://assets.businessdebtadjusters.net/videos/davis-williams.mp4";
  const HUE = 220;

  const videoRef = React.useRef(null);
  const [playing, setPlaying] = React.useState(true);
  const [muted, setMuted] = React.useState(true);

  // Toggle play/mute when user interacts.
  const togglePlay = () => {
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) { v.play(); setPlaying(true); }
    else { v.pause(); setPlaying(false); }
  };
  const toggleMute = (e) => {
    e.stopPropagation();
    const v = videoRef.current;
    if (!v) return;
    v.muted = !v.muted;
    setMuted(v.muted);
  };

  const clip = { name: "Client stories", role: "Verified BDA clients", src: REEL_SRC };

  return (
    <div className="ugc-video">
      <div className="ugc-video-label">
        <span className="live-dot" aria-hidden="true" />
        Owner story
      </div>
      <div
        className="ugc-video-frame"
        onClick={togglePlay}
        role="button"
        tabIndex={0}
        style={{ "--ugc-hue": HUE }}
      >
        {/* === UGC VIDEO ==================================================
           Real CDN clips. Each step shows a different one via UGC_CLIPS.
           ============================================================= */}
        <video
          ref={videoRef}
          className="ugc-video-el"
          autoPlay
          loop
          muted
          playsInline
          preload="metadata"
          src={clip.src}
        ></video>

        <div className="ugc-video-overlay">
          <div className="ugc-watermark" aria-hidden="true">
            <img src="assets/bda-logo-on-navy.png?v=3" alt="" />
          </div>
          <div className="ugc-lower-third">
            <div className="ugc-lt-accent" aria-hidden="true" />
            <div className="ugc-lt-body">
              <div className="ugc-namecard-name">{clip.name}</div>
              <div className="ugc-namecard-role">{clip.role}</div>
            </div>
            <button
              type="button"
              className="ugc-mute"
              aria-label={muted ? "Unmute" : "Mute"}
              onClick={toggleMute}
            >
              {muted ? (
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M11 5 6 9H2v6h4l5 4z"/>
                  <line x1="22" y1="9" x2="16" y2="15"/>
                  <line x1="16" y1="9" x2="22" y2="15"/>
                </svg>
              ) : (
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M11 5 6 9H2v6h4l5 4z"/>
                  <path d="M15.5 8.5a5 5 0 0 1 0 7"/>
                  <path d="M18.5 5.5a9 9 0 0 1 0 13"/>
                </svg>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function StatBlock() {
  return (
    <div className="stat-block">
      <div className="stat">
        <div className="stat-num">$500M<span>+</span></div>
        <div className="stat-lbl">Debt enrolled and negotiated</div>
      </div>
      <div className="stat-rule" />
      <div className="stat">
        <div className="stat-num">11<span> yrs</span></div>
        <div className="stat-lbl">restructuring small-business debt</div>
      </div>
    </div>
  );
}

function AnswerChips({ answers }) {
  // Renders user's filled-in answers as small chips. Keeps the brand panel
  // earning its space as users progress.
  const entries = Object.entries(answers).filter(([, v]) => v != null && v !== "");
  if (entries.length === 0) return null;
  return (
    <div className="answer-strip">
      <div className="answer-strip-label">Your case so far</div>
      <div className="answer-chips">
        {entries.map(([k, v]) => (
          <span className="chip" key={k}>
            <span className="chip-k">{labelFor(k)}</span>
            <span className="chip-v">{formatChipVal(k, v)}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function labelFor(k) {
  return ({
    situation: "Status",
    advanceCount: "Advances",
    balance: "Balance",
    payment: "Payment",
    frequency: "Cadence",
    firstName: "Name",
    businessName: "Business",
    state: "State",
  })[k] || k;
}

function formatChipVal(k, v) {
  if (k === "balance") {
    const map = {
      lt_25k: "<$25k", "25_50k": "$25–50k", "50_100k": "$50–100k",
      "100_250k": "$100–250k", "250_500k": "$250–500k", "500k_1m": "$500k–1M", gt_1m: ">$1M",
    };
    return map[v] || String(v);
  }
  if (k === "payment") {
    const map = {
      lt_500: "<$500", "500_1k": "$500–1k", "1k_2.5k": "$1–2.5k",
      "2.5k_5k": "$2.5–5k", "5k_10k": "$5–10k", gt_10k: ">$10k",
    };
    return map[v] || String(v);
  }
  if (k === "frequency") {
    if (Array.isArray(v)) return v.map((f) => f[0].toUpperCase() + f.slice(1)).join(" + ");
    return v.charAt(0).toUpperCase() + v.slice(1);
  }
  return String(v);
}

function formatCurrency(n) {
  if (typeof n !== "number") n = Number(String(n).replace(/[^0-9.]/g, "")) || 0;
  return "$" + n.toLocaleString("en-US");
}

function PartnerLogos() {
  // Simple monogram-style "as featured in" row. Real logos would replace these.
  const items = ["Forbes", "Bloomberg", "Inc.", "Reuters"];
  return (
    <div className="partner-row">
      <div className="partner-label">Featured in</div>
      <div className="partner-logos">
        {items.map((s) => <span key={s} className="partner-logo">{s}</span>)}
      </div>
    </div>
  );
}

function BrandPanel({ answers, showTestimonial, showOffPage = true, stepIdx = 0, submitted = false }) {
  return (
    <aside className="brand">
      <div className="brand-mark">
        <img src="assets/bda-logo-on-navy.png?v=3" alt="Business Debt Adjusters" className="brand-logo" />
      </div>

      <div style={{ marginTop: 28 }}>
        <div className="eyebrow">MCA Payment Reduction Request Form</div>
        <h1 className="brand-headline">
          A second look at your MCA contract, <em>from advisors who actually read them.</em>
        </h1>
      </div>

      <StatBlock />

      <AnswerChips answers={answers} />

      <UgcVideo stepIdx={stepIdx} submitted={submitted} />

      <PromisesBlock />

      {showTestimonial && <ReviewsCarousel />}

      <div className="footnote">
        <span className="lock" aria-hidden="true" />
        <span>Performance based · No fees upfront · Free contract review</span>
      </div>
    </aside>
  );
}

Object.assign(window, { BrandPanel, DiamondMark, formatCurrency, UGC_CLIPS, UGC_LIBRARY });
