import React, { useEffect, useState } from 'react';
import { FaCircleInfo } from 'react-icons/fa6';
import { FiChevronDown, FiChevronUp } from 'react-icons/fi';

/**
 * localStorage key driving the "How to read this report" open/closed
 * state. Default behavior on first load is open; if the merchant
 * collapses the callout we persist that choice so the page renders
 * the way they last left it on subsequent visits.
 */
const HOW_TO_READ_HIDDEN_KEY = 'recomaze.visibility.howToReadHidden';

interface HowToReadReportProps {
  /** Brand display name shown explicitly in the callout so merchants
   *  immediately see "this report is about <their brand>". */
  brandName: string;
  /** Brand domain - referenced in the body so the connection between
   *  the brand row and the leaderboard rows is unambiguous. */
  brandDomain?: string;
}

/**
 * "How to read this report" callout shown above the AI-visibility
 * report. Collapses into a one-liner on repeat visits, but the first
 * paragraph always names the merchant's brand explicitly so the
 * recurring "I don't see my brand anywhere, is this a bug?" support
 * thread doesn't happen.
 *
 * @param {HowToReadReportProps} props - Component props.
 * @returns {JSX.Element} Callout card.
 */
const HowToReadReport = ({
  brandName,
  brandDomain,
}: HowToReadReportProps): JSX.Element => {
  // Default to expanded; persist a "hidden" choice in localStorage so
  // subsequent loads honor it. Hydrate from storage inside an effect
  // (not initial state) to keep first paint deterministic.
  const [open, setOpen] = useState(true);
  const safeBrandName = brandName?.trim() || 'Your brand';

  useEffect(() => {
    if (typeof window === 'undefined') return;
    try {
      const persistedHidden = window.localStorage.getItem(
        HOW_TO_READ_HIDDEN_KEY
      );

      if (persistedHidden === '1') setOpen(false);
    } catch (_storageError) {
      // localStorage can throw in private mode / disabled storage -
      // fall back to the default-open state silently.
    }
  }, []);

  const toggleOpen = () => {
    setOpen(previousOpen => {
      const nextOpen = !previousOpen;
      try {
        if (typeof window !== 'undefined') {
          if (nextOpen) {
            window.localStorage.removeItem(HOW_TO_READ_HIDDEN_KEY);
          } else {
            window.localStorage.setItem(HOW_TO_READ_HIDDEN_KEY, '1');
          }
        }
      } catch (_storageError) {
        // Ignore - toggle still works in-memory even if we can't
        // persist the choice.
      }
      return nextOpen;
    });
  };

  return (
    <div className="rounded-xl border border-gray-200 bg-white p-4">
      <div className="flex items-start justify-between gap-3 flex-wrap">
        <div className="flex items-start gap-3 min-w-0">
          <span
            aria-hidden="true"
            className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-blue-50 text-blue-600"
          >
            <FaCircleInfo className="h-4 w-4" />
          </span>
          <div className="min-w-0">
            <h2 className="text-sm font-semibold text-gray-900">
              How to read this report
            </h2>
            <p className="mt-0.5 text-xs text-gray-500">
              {`Tracking ${safeBrandName}`}
              {brandDomain ? ` (${brandDomain})` : ''}
              {` against the brands AI assistants surface for your prompts.`}
            </p>
          </div>
        </div>
        <button
          type="button"
          onClick={toggleOpen}
          aria-expanded={open}
          aria-label={
            open ? 'Collapse the explanation' : 'Expand the explanation'
          }
          className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100"
        >
          {open ? <FiChevronUp /> : <FiChevronDown />}
          {open ? 'Hide' : 'Read it'}
        </button>
      </div>

      {open && (
        <div className="mt-3 space-y-3 text-sm text-gray-700">
          <p>
            {`Each Monday we ask 16 prompts (products, scenarios, "best
              of", and geo) to multiple AI assistants and record what
              they say. The numbers below describe how often `}
            <span className="font-semibold">{safeBrandName}</span>
            {` showed up in those answers and how that compares to the
              brands AI mentioned alongside you.`}
          </p>

          <div>
            <p className="text-sm font-semibold text-gray-900">
              What the four KPI cards mean
            </p>
            <p className="mt-1 text-sm text-gray-600">
              Visibility score (0–100): blended health metric. Share of voice: %
              of all brand mentions that pointed to {safeBrandName}. Rank #N of
              M: where {safeBrandName} sits among every brand AI surfaced.
              Sentiment: how AI described you when it did mention you.
            </p>
          </div>

          <div>
            <p className="text-sm font-semibold text-gray-900">
              Share of Voice
            </p>
            <p className="mt-1 text-sm text-gray-600">
              Share of Voice (SOV) ranks 20 brands, with their scores
              distributed as percentages totaling 100%. We display the top 5
              brands, along with a few selected ones from outside the top 5 for
              context. The remaining brands are not shown because their SOV is
              negligible and wouldn{`'`}t add meaningful insight to the view.
            </p>
          </div>

          <div>
            <p className="text-sm font-semibold text-gray-900">
              Why your brand may not appear in the leaderboard
            </p>
            <p className="mt-1 text-sm text-gray-600">
              The Competitors leaderboard only lists rivals AI mentioned this
              week. We always pin a{' '}
              <span className="font-semibold">Your brand</span> row at the top
              so {safeBrandName} is visible side-by-side even when share of
              voice is 0%. That means AI didn&apos;t mention you for any of the
              16 prompts this week, and the &ldquo;Problems detected&rdquo;
              section explains why.
            </p>
          </div>

          <div>
            <p className="text-sm font-semibold text-gray-900">
              What to do next
            </p>
            <p className="mt-1 text-sm text-gray-600">
              Look at &ldquo;Top losses&rdquo; and &ldquo;Problems
              detected&rdquo;. Both list the prompts where AI ignored{' '}
              {safeBrandName}. Use the &ldquo;Generate content&rdquo; buttons on
              a loss to publish a piece of content engineered to win that prompt
              back next week.
            </p>
          </div>
        </div>
      )}
    </div>
  );
};

export default HowToReadReport;
