/* global React, Icons, AI */
// ============================================================
//  Editable field primitives
// ============================================================
const { useState, useRef, useEffect, useCallback } = React;

// auto-growing textarea
function AutoText({ value, onChange, placeholder, className, rows = 1, ...rest }) {
  const ref = useRef(null);
  const resize = useCallback(() => {
    const el = ref.current; if (!el) return;
    el.style.height = "auto"; el.style.height = el.scrollHeight + "px";
  }, []);
  useEffect(() => { resize(); }, [value, resize]);
  return (
    <textarea
      ref={ref} className={`fld ${className || ""}`} value={value} rows={rows}
      placeholder={placeholder} onChange={(e) => { onChange(e.target.value); resize(); }}
      {...rest}
    />
  );
}

function Field({ label, value, onChange, placeholder, mono }) {
  return (
    <label className="field">
      <span className="field-l">{label}</span>
      <input className={`fld ${mono ? "mono" : ""}`} value={value} placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)} />
    </label>
  );
}

// collapsible section
function Section({ icon: Ic, title, children, defaultOpen = true, count, secKey }) {
  const [open, setOpen] = useState(defaultOpen);
  const [flash, setFlash] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!secKey) return;
    const onFocus = (e) => {
      if (!e.detail || e.detail.key !== secKey) return;
      setOpen(true);
      setFlash(false);
      requestAnimationFrame(() => {
        const el = ref.current; if (!el) return;
        const scroller = el.closest(".form-scroll");
        if (scroller) {
          const r = el.getBoundingClientRect();
          const sr = scroller.getBoundingClientRect();
          scroller.scrollTo({ top: scroller.scrollTop + (r.top - sr.top) - 14, behavior: "smooth" });
        }
        requestAnimationFrame(() => setFlash(true));
      });
    };
    window.addEventListener("rb-focus-section", onFocus);
    return () => window.removeEventListener("rb-focus-section", onFocus);
  }, [secKey]);
  useEffect(() => {
    if (!flash) return;
    const t = setTimeout(() => setFlash(false), 1150);
    return () => clearTimeout(t);
  }, [flash]);
  return (
    <div className={`sec ${open ? "open" : ""} ${flash ? "sec-flash" : ""}`} ref={ref} data-form-sec={secKey || undefined}>
      <button className="sec-bar" onClick={() => setOpen((o) => !o)}>
        <span className="sec-ic"><Ic size={16} /></span>
        <span className="sec-name">{title}</span>
        {count != null && <span className="sec-count">{count}</span>}
        <span className="sec-chev"><Icons.arrow size={15} /></span>
      </button>
      {open && <div className="sec-body">{children}</div>}
    </div>
  );
}

// AI mini-menu button for bullets
function AIBulletBtn({ onMode, busy }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h); return () => document.removeEventListener("mousedown", h);
  }, []);
  return (
    <div className="ai-mini" ref={ref}>
      <button className={`bul-ai ${busy ? "busy" : ""}`} title="Improve with AI"
        onClick={() => setOpen((o) => !o)} disabled={busy}>
        {busy ? <Icons.refresh size={14} className="spin" /> : <Icons.magic size={14} />}
      </button>
      {open && !busy && (
        <div className="ai-pop glass">
          {[["improve", "Make it stronger"], ["quantify", "Add metrics"], ["shorten", "Shorten"]].map(([m, l]) => (
            <button key={m} onClick={() => { setOpen(false); onMode(m); }}>
              <Icons.magic size={13} /> {l}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// photo upload field
function PhotoField({ photo, onChange, name }) {
  const inputRef = useRef(null);
  const pick = () => inputRef.current?.click();
  const onFile = (e) => {
    const f = e.target.files?.[0]; if (!f) return;
    const r = new FileReader();
    r.onload = () => onChange(r.result);
    r.readAsDataURL(f);
  };
  const init = (name || "?").trim().split(" ").map((w) => w[0]).slice(0, 2).join("");
  return (
    <div className="photo-field">
      <div className="pf-prev" onClick={pick} style={photo ? { backgroundImage: `url(${photo})` } : null}>
        {!photo && <span>{init}</span>}
        <div className="pf-prev-ov"><Icons.pen size={14} /></div>
      </div>
      <div className="pf-actions">
        <span className="field-l">Profile photo</span>
        <div className="pf-btns">
          <button className="btn btn-ghost btn-sm" onClick={pick}><Icons.user size={14} /> {photo ? "Replace" : "Upload"}</button>
          {photo && <button className="btn btn-quiet btn-sm" onClick={() => onChange(null)}><Icons.trash size={13} /></button>}
        </div>
        <span className="pf-hint">Used by photo templates (Spectrum, Atlas, Onyx, Connect, Globe).</span>
      </div>
      <input ref={inputRef} type="file" accept="image/*" onChange={onFile} hidden />
    </div>
  );
}

// proficiency level picker — 5 dots, click or arrow-key to set 1..5
function LevelPicker({ value, onChange, max = 5 }) {
  const v = Math.max(1, Math.min(max, Math.round(value) || 1));
  return (
    <span className="lvl-pick" role="slider" tabIndex={0}
      aria-valuemin={1} aria-valuemax={max} aria-valuenow={v}
      onKeyDown={(e) => {
        if (e.key === "ArrowRight" || e.key === "ArrowUp") { e.preventDefault(); onChange(Math.min(max, v + 1)); }
        if (e.key === "ArrowLeft" || e.key === "ArrowDown") { e.preventDefault(); onChange(Math.max(1, v - 1)); }
      }}>
      {Array.from({ length: max }, (_, i) => (
        <button key={i} type="button" className={`lvl-dot ${i < v ? "on" : ""}`}
          title={`Level ${i + 1} of ${max}`}
          onClick={() => onChange(i + 1 === v ? Math.max(1, v - 0) : i + 1)} />
      ))}
    </span>
  );
}

Object.assign(window, { AutoText, Field, Section, AIBulletBtn, PhotoField, LevelPicker });
