// How It Works

const HIW_STEPS = [
  {
    num: "01",
    title: "Join Blan",
    desc: "Start by booking a call or subscribing. Whatever works best for you.",
    cta: "View Plans",
    label: "Choose your plan",
  },
  {
    num: "02",
    title: "Submit Tasks",
    desc: "Send in any request — text, video, or files. It takes just minutes to get started.",
    cta: "Submit Now",
    label: "New task",
  },
  {
    num: "03",
    title: "Get Matched",
    desc: "Tasks are assigned to vetted experts based on the project scope and skillset required.",
    cta: "View All Talents",
    label: "Pick your expert",
  },
  {
    num: "04",
    title: "Refine Until Perfect",
    desc: "Receive updates every business day. Refine with unlimited revisions until everything clicks.",
    cta: "Get Started",
    label: "Revision thread",
  },
];

// ── Step 01 ───────────────────────────────────────────────────
const HIW_PLANS = [
  { name: "Starter",    price: "$99",  sub: "1 active task"   },
  { name: "Pro",        price: "$199", sub: "5 active tasks"  },
  { name: "Enterprise", price: "$499", sub: "Unlimited tasks" },
];

const S = {
  planWrap: {
    display: "flex",
    flexDirection: "column",
    gap: "10px",
  },
  planCard: (active) => ({
    display: "flex",
    alignItems: "center",
    gap: "14px",
    padding: "14px 18px",
    borderRadius: "12px",
    cursor: "pointer",
    userSelect: "none",
    backgroundColor: active ? "rgba(255,255,255,0.12)" : "rgba(255,255,255,0.05)",
    border: "1px solid " + (active ? "rgb(253,58,37)" : "rgba(255,255,255,0.12)"),
    boxShadow: active ? "0 0 0 1px rgb(253,58,37)" : "none",
    transition: "all 140ms ease",
  }),
  planName: {
    fontSize: "14px",
    fontWeight: "600",
    lineHeight: "1",
    color: "#fff",
    marginBottom: "5px",
  },
  planSub: {
    fontSize: "11px",
    fontWeight: "500",
    lineHeight: "1",
    color: "rgba(255,255,255,0.45)",
    textTransform: "uppercase",
    letterSpacing: "0.04em",
  },
  planPrice: {
    fontSize: "20px",
    fontWeight: "700",
    lineHeight: "1",
    color: "#fff",
    flexShrink: "0",
  },
  planPriceSub: {
    fontSize: "11px",
    fontWeight: "500",
    color: "rgba(255,255,255,0.38)",
    marginLeft: "3px",
  },
  planCheck: (active) => ({
    width: "22px",
    height: "22px",
    borderRadius: "50%",
    flexShrink: "0",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: active ? "rgb(253,58,37)" : "transparent",
    border: "1.5px solid " + (active ? "transparent" : "rgba(255,255,255,0.22)"),
    transition: "all 140ms ease",
  }),
  planFooter: {
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    gap: "12px",
    paddingTop: "14px",
    marginTop: "4px",
    borderTop: "1px solid rgba(255,255,255,0.08)",
  },
  planFooterLabel: {
    fontSize: "11px",
    fontWeight: "500",
    color: "rgba(255,255,255,0.45)",
    textTransform: "uppercase",
    letterSpacing: "0.05em",
  },
  planFooterName: {
    color: "#fff",
    fontWeight: "700",
  },
};

const CheckSVG = () => (
  <svg viewBox="0 0 12 12" width="11" height="11" fill="none"
    stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
    <polyline points="2,6 5,9 10,3" />
  </svg>
);

const PreviewStep1 = ({ lang }) => {
  const [selIdx, setSelIdx] = React.useState(1);

  const planName = (i) => t('howItWorks.plans.items.' + i + '.name', lang) || HIW_PLANS[i].name;
  const planSub  = (i) => t('howItWorks.plans.items.' + i + '.sub',  lang) || HIW_PLANS[i].sub;

  return (
    <div style={S.planWrap}>
      {HIW_PLANS.map((p, i) => {
        const active = selIdx === i;
        return (
          <div key={p.name} style={S.planCard(active)} onClick={() => setSelIdx(i)}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={S.planName}>{planName(i)}</div>
              <div style={S.planSub}>{planSub(i)}</div>
            </div>
            <div style={S.planPrice}>
              {p.price}
              <span style={S.planPriceSub}>{t('howItWorks.plans.perMonth', lang)}</span>
            </div>
            <div style={S.planCheck(active)}>
              {active && <CheckSVG />}
            </div>
          </div>
        );
      })}
      <div style={S.planFooter}>
        <span style={S.planFooterLabel}>
          {t('howItWorks.plans.planLabel', lang)} <span style={S.planFooterName}>{planName(selIdx)}</span>
        </span>
        <Button variant="accent">{t('howItWorks.plans.continueWith', lang)} {planName(selIdx)}</Button>
      </div>
    </div>
  );
};

// ── Step 02 ───────────────────────────────────────────────────
const HIW_CATS       = ["Design", "Branding", "Web", "Copy", "Video", "Motion"];
const HIW_PRIORITIES = ["Low", "Medium", "High", "Urgent"];

const PreviewStep2 = ({ lang }) => {
  const [taskName, setTaskName] = React.useState("");
  const [cats, setCats]         = React.useState(["Design"]);
  const [priority, setPriority] = React.useState("High");
  const [tasks, setTasks]       = React.useState([]);
  const listRef = React.useRef(null);

  const catLabel      = (key) => t('howItWorks.step2.cats.'      + HIW_CATS.indexOf(key),       lang) || key;
  const priorityLabel = (key) => t('howItWorks.step2.priorities.' + HIW_PRIORITIES.indexOf(key), lang) || key;

  const toggleCat = (c) =>
    setCats((prev) => prev.includes(c) ? prev.filter((x) => x !== c) : [...prev, c]);

  const addTask = () => {
    const name = taskName.trim();
    if (!name) return;
    setTasks((prev) => [...prev, { id: Date.now(), name, cats: [...cats], priority }]);
    setTaskName("");
    setTimeout(() => {
      if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
    }, 50);
  };

  return (
    <div className="ag-hiw__mock ag-hiw__mock--submit">
      <div className="ag-hiw__task-form">
        <input
          className="ag-hiw__input"
          placeholder={t('howItWorks.step2.placeholder', lang)}
          value={taskName}
          onChange={(e) => setTaskName(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && addTask()}
        />
        <div className="ag-hiw__chip-row">
          {HIW_CATS.map((c) => (
            <button key={c} type="button"
              className={"ag-hiw__toggle-chip" + (cats.includes(c) ? " is-on" : "")}
              onClick={() => toggleCat(c)}
            >{catLabel(c)}</button>
          ))}
        </div>
        <div className="ag-hiw__task-bottom-row">
          <div className="ag-hiw__chip-row">
            {HIW_PRIORITIES.map((p) => (
              <button key={p} type="button"
                className={"ag-hiw__toggle-chip ag-hiw__toggle-chip--sm" + (priority === p ? " is-on" : "")}
                onClick={() => setPriority(p)}
              >{priorityLabel(p)}</button>
            ))}
          </div>
          <button type="button" className="ag-hiw__send-btn" onClick={addTask} aria-label="Add task">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
              <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
            </svg>
          </button>
        </div>
      </div>
      {tasks.length > 0 && (
        <div className="ag-hiw__task-list" ref={listRef}>
          {tasks.map((task) => (
            <div key={task.id} className="ag-hiw__task-item ag-hiw__msg--new">
              <div className="ag-hiw__task-item-left">
                <span className="ag-hiw__task-item-name">{task.name}</span>
                <div className="ag-hiw__chip-row">
                  {task.cats.slice(0, 2).map((c) => (
                    <span key={c} className="ag-hiw__toggle-chip is-on ag-hiw__toggle-chip--xs">{catLabel(c)}</span>
                  ))}
                  <span className="ag-hiw__priority-badge" data-p={task.priority}>{priorityLabel(task.priority)}</span>
                </div>
              </div>
              <button type="button" className="ag-hiw__remove-btn"
                onClick={() => setTasks((prev) => prev.filter((x) => x.id !== task.id))}
                aria-label="Remove task"
              >×</button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ── Step 03 ───────────────────────────────────────────────────
const HIW_EXPERTS = [
  { name: "Aria Chen",   role: "Senior Product Designer", rating: "4.9", skills: ["UI Design", "Branding", "Motion"], avatar: "assets/reviews/testimonials-1.jpg" },
  { name: "Marcus Lee",  role: "Brand & Visual Designer", rating: "4.8", skills: ["Branding", "Identity", "Print"],   avatar: "assets/reviews/testimonials-2.jpg" },
  { name: "Yuki Tanaka", role: "UX/UI Designer",          rating: "5.0", skills: ["Research", "Wireframes"],          avatar: "assets/reviews/testimonials-3.jpg" },
  { name: "Cleo Davis",  role: "Motion Designer",          rating: "4.7", skills: ["Animation", "Video", "3D"],        avatar: "assets/reviews/testimonials-4.jpg" },
  { name: "Omar Haddad", role: "Frontend Designer",        rating: "4.9", skills: ["Web Design", "Design Systems"],   avatar: "assets/reviews/testimonials-5.jpg" },
  { name: "Priya Nair",  role: "Illustration & Brand",     rating: "4.8", skills: ["Illustration", "Iconography"],    avatar: "assets/reviews/testimonials-6.jpg" },
];

const PreviewStep3 = ({ lang }) => {
  const [selected, setSelected] = React.useState(null);
  return (
    <div className="ag-hiw__mock ag-hiw__mock--match">
      <div className="ag-hiw__expert-list">
        {HIW_EXPERTS.map((e, i) => (
          <button key={e.name} type="button"
            className={"ag-hiw__expert-card" + (selected === i ? " is-selected" : "")}
            onClick={() => setSelected(selected === i ? null : i)}
            aria-pressed={selected === i}
          >
            <span className="ag-avatar" role="img" aria-label={e.name}
              style={{ width: 36, height: 36, flex: "0 0 36px", backgroundImage: `url('${e.avatar}')` }}
            />
            <div className="ag-hiw__expert-info">
              <div className="ag-hiw__expert-name">{e.name}</div>
              <div className="ag-hiw__expert-role">{t('howItWorks.step3.roles.' + i, lang) || e.role}</div>
              <div className="ag-hiw__chip-row" style={{ marginTop: 4 }}>
                {e.skills.map((s) => (
                  <span key={s} className="ag-hiw__toggle-chip ag-hiw__toggle-chip--xs">{s}</span>
                ))}
              </div>
            </div>
            <div className="ag-hiw__expert-right">
              <span className="ag-hiw__expert-rating">★ {e.rating}</span>
              <span className={"ag-hiw__select-badge" + (selected === i ? " is-on" : "")}>
                {selected === i ? t('howItWorks.step3.selected', lang) : t('howItWorks.step3.select', lang)}
              </span>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
};

// ── Step 04 ───────────────────────────────────────────────────
const HIW_SEED_MSGS = [
  { id: 1, from: "client",   textKey: "msg1", timeKey: "yesterday", timeSuffix: " · 2:30 PM", avatar: "assets/reviews/testimonials-3.jpg" },
  { id: 2, from: "designer", textKey: "msg2", timeKey: "today",     timeSuffix: " · 9:15 AM", file: "landing_v3.fig", statusKey: "approved", avatar: "assets/reviews/testimonials-1.jpg" },
];

const PreviewStep4 = ({ lang }) => {
  const [messages, setMessages] = React.useState(HIW_SEED_MSGS);
  const [input, setInput]       = React.useState("");
  const listRef = React.useRef(null);

  React.useEffect(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [messages]);

  const send = () => {
    const text = input.trim();
    if (!text) return;
    setMessages((prev) => [
      ...prev,
      { id: Date.now(), from: "client", text, timeKey: "justNow", isNew: true, avatar: "assets/reviews/testimonials-3.jpg" },
    ]);
    setInput("");
  };

  return (
    <div className="ag-hiw__chat">
      <div className="ag-hiw__chat-messages" ref={listRef}>
        {messages.map((m) => (
          <div key={m.id}
            className={"ag-hiw__msg" + (m.from === "designer" ? " ag-hiw__msg--reply" : "") + (m.isNew ? " ag-hiw__msg--new" : "")}
          >
            <span className="ag-avatar" role="img"
              aria-label={m.from === "client" ? "You" : "Designer"}
              style={{ width: 32, height: 32, flex: "0 0 32px", backgroundImage: `url('${m.avatar}')` }}
            />
            <div className={"ag-hiw__msg-bubble" + (m.from === "designer" ? " ag-hiw__msg-bubble--reply" : "")}>
              <p className="ag-hiw__msg-text">{m.textKey ? t('howItWorks.step4.' + m.textKey, lang) : m.text}</p>
              {m.file && <div className="ag-hiw__msg-file"><span>↓</span> {m.file}</div>}
              <div className="ag-hiw__msg-foot">
                <span className="ag-hiw__msg-time">
                  {m.timeKey ? (t('howItWorks.step4.' + m.timeKey, lang) + (m.timeSuffix || '')) : m.time}
                </span>
                {m.statusKey && <span className="ag-chip ag-chip--dark">{t('howItWorks.step4.' + m.statusKey, lang)}</span>}
              </div>
            </div>
          </div>
        ))}
      </div>
      <div className="ag-hiw__chat-form">
        <input className="ag-hiw__input" placeholder={t('howItWorks.step4.placeholder', lang)}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && send()}
        />
        <button type="button" className="ag-hiw__send-btn" onClick={send} aria-label="Send">
          <svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor">
            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
          </svg>
        </button>
      </div>
    </div>
  );
};

const HIW_PANELS = [PreviewStep1, PreviewStep2, PreviewStep3, PreviewStep4];

// ── Accordion step ────────────────────────────────────────────
const HIWStep = ({ num, title, desc, cta, open, onToggle, onCTA }) => (
  <div className={"ag-hiw__step" + (open ? " is-open" : "")}>
    <button className="ag-hiw__step-row" onClick={onToggle}
      aria-expanded={open} type="button">
      <span className="ag-hiw__step-num">{num}</span>
      <span className="ag-hiw__step-title">{title}</span>
      <span className="ag-hiw__step-icon" aria-hidden="true">
        <svg viewBox="0 0 24 24" width="14" height="14" fill="none"
          stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="6,9 12,15 18,9"/>
        </svg>
      </span>
    </button>
    {open && (
      <div className="ag-hiw__step-body">
        <p className="ag-hiw__step-desc">{desc}</p>
        <Button variant="dark" onClick={onCTA}>{cta}</Button>
      </div>
    )}
  </div>
);

// ── Section ───────────────────────────────────────────────────
const HowItWorks = ({ data, lang }) => {
  const hasSection = data !== null && data !== undefined;
  const steps = hasSection
    ? (Array.isArray(data) ? data.map((s, i) => ({
        num:   String(i + 1).padStart(2, '0'),
        title: i18(s.title, lang) || '',
        desc:  i18(s.desc, lang)  || '',
        cta:   s.cta ? i18(s.cta.label, lang) || 'Get Started' : 'Get Started',
        label: i18(s.label, lang) || t('howItWorks.steps.' + i + '.label', lang),
      })) : [])
    : (window.TRANSLATIONS?.howItWorks?.steps || HIW_STEPS).map((_, i) => ({
        num:   String(i + 1).padStart(2, '0'),
        title: t('howItWorks.steps.' + i + '.title', lang),
        desc:  t('howItWorks.steps.' + i + '.desc',  lang),
        cta:   t('howItWorks.steps.' + i + '.cta',   lang),
        label: t('howItWorks.steps.' + i + '.label', lang),
      }));

  const [activeIdx, setActiveIdx] = React.useState(0);
  const scrollTo = (id) =>
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });

  const ActivePanel = HIW_PANELS[activeIdx];

  return (
    <section className="ag-hiw" id="ag-section-how">
      <SectionHeading
        eyebrow={t('howItWorks.eyebrow', lang)}
        sub={t('howItWorks.sub', lang)}
      >
        {t('howItWorks.heading', lang)}
      </SectionHeading>

      <div className="ag-hiw__grid">

        <div className="ag-hiw__steps">
          {steps.map((step, i) => (
            <HIWStep
              key={step.num}
              {...step}
              open={activeIdx === i}
              onToggle={() => setActiveIdx(activeIdx === i ? 0 : i)}
              onCTA={() => scrollTo("ag-section-contact")}
            />
          ))}
        </div>

        <div className="ag-hiw__preview">
          <header className="ag-hiw__preview-head">
            <span className="ag-hiw__preview-step">{t('howItWorks.stepLabel', lang)} {steps[activeIdx].num} {t('howItWorks.stepOf', lang)} {String(steps.length).padStart(2, '0')}</span>
            <span className="ag-hiw__preview-label">{steps[activeIdx].label}</span>
          </header>
          <div className="ag-hiw__panels">
            <ActivePanel lang={lang} />
          </div>
        </div>

      </div>
    </section>
  );
};

window.HowItWorks = HowItWorks;
