/* Shared primitives + routing for the consolidated MAF flow.
   Lives in window.MAF (alongside the data on window.MAF_DATA). */

const { createContext, useContext, useState, useEffect, useMemo, useRef, useCallback } = React;

/* ============================================================
   Routing — simple hash router
   ============================================================ */
const RouteContext = createContext(null);

function parseHash() {
  const h = window.location.hash.replace(/^#\/?/, '');
  if (!h) return { name: 'splash' };
  const [name, ...rest] = h.split('/');
  const params = {};
  for (let i = 0; i < rest.length; i += 2) {
    if (rest[i]) params[rest[i]] = decodeURIComponent(rest[i+1] || '');
  }
  return { name, ...params };
}
function stringifyRoute(r) {
  const { name, ...rest } = r;
  const tail = Object.entries(rest).map(([k,v]) => `${k}/${encodeURIComponent(v)}`).join('/');
  return '#/' + name + (tail ? '/' + tail : '');
}

function RouteProvider({ children }) {
  const [route, setRoute] = useState(parseHash());
  useEffect(() => {
    const onHash = () => setRoute(parseHash());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  const navigate = useCallback((name, params = {}) => {
    const r = { name, ...params };
    window.location.hash = stringifyRoute(r);
    // scroll to top of new screen
    requestAnimationFrame(() => window.scrollTo({ top: 0, behavior: 'instant' }));
  }, []);
  return (
    <RouteContext.Provider value={{ route, navigate }}>
      {children}
    </RouteContext.Provider>
  );
}
const useRoute = () => useContext(RouteContext);

/* ============================================================
   Data access
   ============================================================ */
const DATA = window.MAF_DATA;
function useData() { return DATA; }
function useLot(n) {
  const data = useData();
  return data.lots.find(l => String(l.n) === String(n)) || null;
}
function useBuilder(id) {
  const data = useData();
  return data.builders.find(b => b.id === id) || null;
}

/* ============================================================
   Visual primitives (reuse styles.css)
   ============================================================ */
const Img = ({ label, h, w, dark, style, children, onClick }) => (
  <div
    className={"wf-img" + (dark ? " wf-img-dark" : "")}
    style={{ height: h, width: w, cursor: onClick ? 'pointer' : undefined, ...style }}
    onClick={onClick}
  >
    {label && <span className="wf-img-label">{label}</span>}
    {children}
  </div>
);
const Bar = ({ w = "60%", h = 10, mt = 0, style }) => (
  <div className={"wf-bar" + (h <= 6 ? " wf-bar-sm" : h >= 14 ? " wf-bar-lg" : "")}
       style={{ width: w, height: h, marginTop: mt, ...style }} />
);
const Bars = ({ widths = ["95%","88%","70%"], gap = 8 }) => (
  <div style={{ display: "flex", flexDirection: "column", gap }}>
    {widths.map((w, i) => <Bar key={i} w={w} h={8} />)}
  </div>
);
const Eyebrow = ({ children, color, style, onClick }) => (
  <div className="t-eyebrow" style={{ color, cursor: onClick ? 'pointer' : undefined, ...style }} onClick={onClick}>{children}</div>
);
const Note = ({ children, style }) => (
  <div className="t-note" style={style}>{children}</div>
);

/* MF monogram — small circle fallback when the script wordmark won't fit. */
const MFMark = ({ size = 28, color = "var(--neutral-900)" }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" aria-hidden="true">
    <circle cx="16" cy="16" r="15" fill="none" stroke={color} strokeWidth="1" />
    <text x="16" y="20.5" textAnchor="middle"
          fontFamily="Playfair Display, serif"
          fontWeight="500"
          fontSize="13"
          fill={color}>MF</text>
  </svg>
);

/* The real Madison Fields script wordmark.
   `dark` swaps the source for an inverted (light-on-dark) treatment via CSS filter. */
const Wordmark = ({ height = 28, dark = false, style, onClick }) => (
  <img
    src={(typeof window !== 'undefined' && window.__resources && window.__resources.logo) || 'assets/madison-fields-logo.png'}
    alt="Madison Fields"
    height={height}
    onClick={onClick}
    style={{
      height,
      width: 'auto',
      display: 'block',
      filter: dark ? 'invert(1) brightness(1.4)' : 'none',
      cursor: onClick ? 'pointer' : undefined,
      ...style,
    }}
  />
);

/* TopNav — works with router. variant 'translucent' overlays the hero. */
function TopNav({ variant = "default" }) {
  const { route, navigate } = useRoute();
  const links = [
    ['siteplan', 'Site Plan'],
    ['builders', 'Builders'],
    ['plans', 'Floor Plans'],
    ['pattern', 'Pattern Book'],
    ['faq', 'FAQ'],
  ];
  const isActive = (name) => {
    if (name === 'siteplan' && (route.name === 'siteplan' || route.name === 'lot')) return true;
    if (name === 'builders' && (route.name === 'builders' || route.name === 'builder')) return true;
    if (name === 'plans' && (route.name === 'plans' || route.name === 'plan')) return true;
    return route.name === name;
  };
  return (
    <div className="wf-topnav" style={{
      background: variant === "translucent" ? "rgba(251,251,249,0.92)" : "var(--bg-primary)",
      backdropFilter: variant === "translucent" ? "blur(10px)" : undefined,
      position: variant === "translucent" ? "absolute" : "relative",
      top: 0, left: 0, right: 0, zIndex: 10,
      borderBottom: "1px solid var(--neutral-200)",
    }}>
      <div style={{ cursor: 'pointer' }} onClick={() => navigate('landing')}>
        <Wordmark height={26} />
      </div>
      <div className="wf-navlinks" style={{ marginLeft: 32 }}>
        {links.map(([k, l]) => (
          <div key={k}
               onClick={() => navigate(k)}
               style={{
                 color: isActive(k) ? "var(--neutral-900)" : "var(--neutral-500)",
                 borderBottom: isActive(k) ? "1px solid var(--neutral-900)" : "1px solid transparent",
                 paddingBottom: 4,
                 cursor: "pointer"
               }}>{l}</div>
        ))}
      </div>
      <div style={{ marginLeft: "auto" }} className="row gap-4 center">
        <span className="t-meta">Caroline H.</span>
        <div style={{
          width: 28, height: 28, borderRadius: "50%",
          border: "1px solid var(--neutral-300)",
          background: "var(--neutral-100)"
        }} />
      </div>
    </div>
  );
}

function Footer() {
  const { navigate } = useRoute();
  return (
    <div className="wf-footer" style={{ padding: 32 }}>
      <div className="row between" style={{ alignItems: "flex-end" }}>
        <div className="col gap-3">
          <div style={{ cursor: 'pointer' }} onClick={() => navigate('landing')}>
            <Wordmark height={32} />
          </div>
          <div className="t-meta" style={{ color: "var(--neutral-500)" }}>Athens, Georgia · 300 acres · adjacent to The Rose Golf Club</div>
        </div>
        <div className="row gap-8" style={{ color: "var(--neutral-500)" }}>
          <div className="col gap-2">
            <div className="t-meta">Walkthrough</div>
            <Eyebrow style={{ cursor: 'pointer' }} onClick={() => navigate('siteplan')}>Site plan →</Eyebrow>
            <Eyebrow style={{ cursor: 'pointer' }} onClick={() => navigate('builders')}>Builders →</Eyebrow>
            <Eyebrow style={{ cursor: 'pointer' }} onClick={() => navigate('plans')}>Floor plans →</Eyebrow>
          </div>
          <div className="col gap-2">
            <div className="t-meta">Process</div>
            <Eyebrow style={{ cursor: 'pointer' }} onClick={() => navigate('pattern')}>Pattern Book →</Eyebrow>
            <Eyebrow style={{ cursor: 'pointer' }} onClick={() => navigate('faq')}>FAQ →</Eyebrow>
          </div>
          <div className="col gap-2">
            <div className="t-meta">Contact</div>
            <Eyebrow>Dimitri Cassini · 770.355.6540</Eyebrow>
            <Eyebrow>Bonneau Ansley · 404.906.3161</Eyebrow>
            <Eyebrow>Nick Cassini · 404.906.2151</Eyebrow>
            <Eyebrow>General · 404.480.HOME</Eyebrow>
          </div>
        </div>
      </div>
    </div>
  );
}

/* Status chip + helpers */
const STATUS_LABEL = {
  available: 'Available',
  reserved: 'Reserved',
  sold: 'Sold',
  soon: 'Coming soon',
};
const STATUS_DOT = {
  available: 'sage', reserved: 'amber', sold: 'stone', soon: 'cream',
};
const STATUS_FILL = {
  available: 'rgba(138,154,123,0.42)',
  reserved:  'rgba(200,154,58,0.45)',
  sold:      'rgba(168,162,158,0.55)',
  soon:      'rgba(241,217,166,0.55)',
};
const STATUS_STROKE = {
  available: '#8a9a7b',
  reserved:  '#c89a3a',
  sold:      '#78716c',
  soon:      '#c9a861',
};
const STATUS_FILL_HOVER = {
  available: 'rgba(138,154,123,0.7)',
  reserved:  'rgba(200,154,58,0.7)',
  sold:      'rgba(168,162,158,0.78)',
  soon:      'rgba(241,217,166,0.85)',
};

const StatusChip = ({ tone, label, count }) => {
  return (
    <div className="row gap-2 center" style={{ fontFamily: "var(--font-sans)", fontSize: 12 }}>
      <span className={`wf-dot wf-dot-${tone}`} />
      <span style={{ color: "var(--neutral-800)", fontWeight: 500 }}>{label}</span>
      {count != null && <span style={{ color: "var(--neutral-400)" }}>{count}</span>}
    </div>
  );
};

const fmtPrice = (p) => p >= 1_000_000
  ? '$' + (p / 1_000_000).toFixed(2).replace(/\.?0+$/, '') + 'M'
  : '$' + Math.round(p / 1000) + 'k';

window.MAF = {
  RouteProvider, RouteContext, useRoute,
  useData, useLot, useBuilder,
  Img, Bar, Bars, Eyebrow, Note, MFMark, Wordmark,
  TopNav, Footer, StatusChip,
  STATUS_LABEL, STATUS_DOT, STATUS_FILL, STATUS_STROKE, STATUS_FILL_HOVER,
  fmtPrice,
};
