// ============ Diagnostic.jsx ============
// Hidden Revenue Diagnostic — 7-step qualifier funnel for prospective
// clinical practices. Voice: Malca Consulting — orthodontic / specialist
// private practices, burgundy + cream brand, Tiempos serif headlines.

const STEPS = [
{
  eyebrow: "Step 1 of 7",
  question: <React.Fragment>Are you actively trying to grow <em>high-value treatment revenue</em>?</React.Fragment>,
  sub: "This helps us understand whether growth is actually a priority right now.",
  key: "intent",
  options: [
  { label: "Yes — we want to grow", value: "yes" },
  { label: "No — we're absolutely full", value: "full" }],

  insightTitle: "Growth is only useful when the practice can absorb it.",
  insight: "For some practices, the next step is not more volume. It is more control. The question is whether growth would strengthen the practice — or simply add more pressure to the owner, the team, and the patient journey."
},
{
  eyebrow: "Step 2 of 7",
  question: <React.Fragment>Do you have past enquiries, consultations, or treatment plans that <em>never converted</em>?</React.Fragment>,
  sub: "This helps us understand whether there is value already sitting inside the practice.",
  key: "database",
  options: [
  { label: "Yes — we have a database", value: "strong" },
  { label: "Yes — but it is not organized", value: "some" },
  { label: "No — we don't have a database", value: "none" }],

  insightTitle: "Not every patient who paused is a lost patient.",
  insight: "High-value treatment decisions often take time. Some patients need reassurance, timing, education, financing clarity, or simply a structured follow-up path. The opportunity is often not in finding completely new interest — but in returning to interest that already existed."
},
{
  eyebrow: "Step 3 of 7",
  question: <React.Fragment>How many <em>inactive leads</em>, past enquiries, or unconverted consultations are in your database?</React.Fragment>,
  sub: "An approximate count is enough — we will refine it during the review.",
  key: "dbSize",
  options: [
  { label: "Under 100", value: 50 },
  { label: "100–300", value: 200 },
  { label: "300–700", value: 500 },
  { label: "700–1,500", value: 1100 },
  { label: "1,500+", value: 2000 },
  { label: "We don't have a database", value: 0 }],

  insightTitle: "Your database may be one of the most underused assets in the practice.",
  insight: "A list of past enquiries is not just old admin. It can reveal how much demand the practice has already generated, how much was never followed through, and whether there is enough existing opportunity to justify a structured reactivation effort."
},
{
  eyebrow: "Step 4 of 7",
  question: <React.Fragment>Of the patients who come in for a consultation, <em>how many start treatment</em>?</React.Fragment>,
  sub: "Of all the patients who visit your practice in person for a high-value consultation — how many actually begin treatment?",
  key: "conversion",
  options: [
  { label: "Less than 30%", value: 0.22 },
  { label: "30–50%", value: 0.40 },
  { label: "50–70%", value: 0.60 },
  { label: "70%+", value: 0.75 }],

  insightTitle: "The consultation is where clinical value has to become a clear decision.",
  insight: "When patients attend a consultation but do not start, the issue is rarely interest alone. It can be the way the treatment is explained, how urgency is created, how objections are handled, how follow-up is owned, or how confidently the next step is structured."
},
{
  eyebrow: "Step 5 of 7",
  question: <React.Fragment>How many <em>new Invisalign or orthodontic cases</em> per month would you like to add?</React.Fragment>,
  sub: "Choose the level of growth that would feel meaningful and realistic for your practice.",
  key: "volume",
  options: [
  { label: "3–5 new cases / month", value: 4 },
  { label: "6–10 new cases / month", value: 8 },
  { label: "11–20 new cases / month", value: 15 },
  { label: "20+ new cases / month", value: 25 }],

  insightTitle: "A good growth target has to match the operating reality.",
  insight: "The strongest target is not always the biggest one. It is the number the practice can actually support with chair time, treatment coordination, follow-up, financing conversations, and team ownership — without creating chaos behind the scenes."
},
{
  eyebrow: "Step 6 of 7",
  question: <React.Fragment>What is your <em>average Invisalign or orthodontic case fee</em>?</React.Fragment>,
  sub: "The total amount a patient pays for a full treatment plan.",
  key: "fee",
  options: [
  { label: "CHF 4,000–5,500", value: 4750 },
  { label: "CHF 5,500–7,000", value: 6250 },
  { label: "CHF 7,000–9,000", value: 8000 },
  { label: "CHF 9,000+", value: 10000 }],

  insightTitle: "In high-value treatment, small system improvements can have a large commercial effect.",
  insight: "When each accepted case is worth several thousand francs, revenue does not only increase through more enquiries. It can increase through better reactivation, faster booking, stronger consultation conversion, and more consistent follow-up."
},
{
  eyebrow: "Step 7 of 7",
  question: <React.Fragment>How many <em>in-person consultations</em> can your practice realistically handle per week?</React.Fragment>,
  sub: "Be realistic — this helps size the system correctly for your team.",
  key: "capacity",
  options: [
  { label: "1–3 per week", value: 2 },
  { label: "4–7 per week", value: 5.5 },
  { label: "8–12 per week", value: 10 },
  { label: "13–20 per week", value: 16.5 },
  { label: "20+ per week", value: 24 }],

  insightTitle: "Capacity protects quality.",
  insight: "A serious growth system should not flood the calendar blindly. It should match opportunity to what the team can actually handle — so the practice creates more treatment starts without weakening the patient experience or increasing owner dependency."
}];


// ---------------- Fit logic ----------------
function computeFit(a) {
  const wantsGrowth = a.intent === "yes";
  const dbStrong = a.database === "strong";
  const dbSome = a.database === "some";
  const dbNone = a.database === "none";
  const dbSize = a.dbSize || 0;
  const fee = a.fee || 0;
  const capacity = a.capacity || 0;
  const volume = a.volume || 0;
  const conversion = (a.conversion == null) ? 0.30 : a.conversion;

  // Low-fit
  if (a.intent === "full") return "low";
  // No database to reactivate — our core service does not apply
  if (dbNone || dbSize === 0) return "nodb";
  // Strong reactivation fit
  if (wantsGrowth && dbSize >= 100 && fee >= 4750 && capacity >= 4) {
    return "strong";
  }
  // Medium-fit catches the rest of the growth-minded cases
  return "medium";
}

const FIT_COPY = {
  strong: {
    title: <React.Fragment>Your practice looks like a <em>strong fit for database reactivation</em>.</React.Fragment>,
    body: "Your answers suggest there is already meaningful treatment interest sitting inside the practice — past enquiries, unconverted consultations, paused treatment plans. With your fee level and consultation capacity, a structured reactivation system could return measurable revenue before any new acquisition spend.",
    cta: "Request my practice review"
  },
  medium: {
    title: <React.Fragment>There is likely an opportunity, but the <em>system needs diagnosis first</em>.</React.Fragment>,
    body: "Your answers suggest there may be commercial potential, but the constraint is not yet obvious. The first move may be organizing the database for reactivation, improving consultation conversion, or sizing growth around the practice's actual capacity — before adding any new demand.",
    cta: "Request my practice review"
  },
  nodb: {
    title: <React.Fragment>Our system <em>may not be the right fit right now</em>.</React.Fragment>,
    body: "Malca's primary work is rebuilding the commercial system around the practice's existing patient interest — past enquiries, unconverted consultations, and paused treatment plans. Without a database to reactivate, the work would need to start with new acquisition, which is not the strongest use of an engagement at this stage.",
    cta: "Request a private review"
  },
  low: {
    title: <React.Fragment>This may not be the right moment for a <em>full commercial system</em>.</React.Fragment>,
    body: "Your answers suggest that the immediate priority may not be building a larger commercial system. Before increasing volume, the practice may need more clarity around capacity, treatment focus, or whether growth is actually desired right now.",
    cta: "Request a private review"
  }
};


const DiagnosticPage = ({ onNavigate }) => {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [contact, setContact] = React.useState({
    name: "", email: "", practice: "", website: "", city: "", focus: ""
  });
  const topRef = React.useRef(null);

  const totalSteps = 8;
  const progress = Math.round((step + 1) / totalSteps * 100);

  React.useEffect(() => {
    if (topRef.current) topRef.current.scrollIntoView({ behavior: "smooth", block: "start" });
  }, [step]);

  const choose = (key, value) => {
    setAnswers((a) => ({ ...a, [key]: value }));
    setTimeout(() => setStep((s) => Math.min(s + 1, 7)), 220);
  };

  const back = () => setStep((s) => Math.max(s - 1, 0));

  // ----- projection math -----
  const targetCases = answers.volume || 8;
  const conversion = (answers.conversion == null) ? 0.30 : answers.conversion;
  const fee = answers.fee || 6250;
  const weeklyCapacity = answers.capacity || 5.5;
  const monthlyCapacity = Math.round(weeklyCapacity * 4.3);
  const estRevenue = targetCases * fee;
  // Reactivation potential: dbSize × ~8% conversion rate × fee.
  // 8% is a conservative midpoint for unconverted clinical enquiries that
  // are reactivated through a structured cadence — used as an indicative
  // (not promised) one-time opportunity figure.
  const dbSize = answers.dbSize || 0;
  const reactivationCases = Math.round(dbSize * 0.08);
  const reactivationRevenue = reactivationCases * fee;
  const fmt = (n) => "CHF " + n.toLocaleString("fr-CH").replace(/,/g, "\u202f");

  const fit = computeFit(answers);
  const fitCopy = FIT_COPY[fit];

  const submit = (e) => {
    e.preventDefault();
    setSent(true);
  };

  return (
    <main data-screen-label="Diagnostic" className="mc-diag-page">
      <div className="mc-diag-topbar mc-shell">
        <button className="mc-diag-return" onClick={() => onNavigate("home")} aria-label="Return to home">
          <span aria-hidden="true">←</span>
          <span>Return</span>
        </button>
        <button className="mc-diag-mark" onClick={() => onNavigate("home")} aria-label="Malca consulting — home">
          <img src="assets/logo-malca-consulting.png" alt="" />
        </button>
        <span className="mc-diag-topbar-meta">Hidden Revenue Diagnostic</span>
      </div>
      <section className="mc-diag-hero mc-shell">
        <div className="mc-diag-hero-pill">
          <span className="dot" />
          For orthodontic and specialist clinical practices
        </div>
        <p className="mc-diag-hero-sub">
          A short diagnostic for owner-led clinical practices to understand whether treatment revenue is being lost inside the database, consultation path, or follow-up system.
        </p>
      </section>

      <section className="mc-shell" style={{ paddingBottom: 96 }}>
        <div className="mc-diag-card" ref={topRef}>
          <div className="mc-diag-progress-head">
            <span className="mc-diag-progress-label">{step < 7 ? `Step ${step + 1} of 7` : "Your private practice review"}</span>
            <span className="mc-diag-progress-pct">{Math.min(progress, 100)}%</span>
          </div>
          <div className="mc-diag-progress-track">
            <div className="mc-diag-progress-fill" style={{ width: `${Math.min(progress, 100)}%` }} />
          </div>

          {step < 7 &&
          <QuestionView step={STEPS[step]} answers={answers} onChoose={choose} onBack={step > 0 ? back : null} />
          }

          {step === 7 && !sent &&
          <ResultsView
            answers={answers}
            fit={fit}
            fitCopy={fitCopy}
            targetCases={targetCases}
            conversion={conversion}
            fee={fee}
            monthlyCapacity={monthlyCapacity}
            estRevenue={estRevenue}
            dbSize={dbSize}
            reactivationCases={reactivationCases}
            reactivationRevenue={reactivationRevenue}
            fmt={fmt}
            contact={contact}
            setContact={setContact}
            onSubmit={submit}
            onBack={back} />
          }

          {step === 7 && sent &&
          <SentView
            estRevenue={estRevenue}
            targetCases={targetCases}
            fmt={fmt}
            onNavigate={onNavigate} />
          }
        </div>
      </section>
    </main>);

};

// -------------------- QUESTION VIEW --------------------
const QuestionView = ({ step, answers, onChoose, onBack }) => {
  const current = answers[step.key];
  return (
    <div className="mc-diag-step">
      <h2 className="mc-diag-q">{step.question}</h2>
      <p className="mc-diag-q-sub">{step.sub}</p>

      <ul className="mc-diag-options">
        {step.options.map((o, i) => {
          const letter = String.fromCharCode(65 + i);
          const isSelected = current === o.value;
          return (
            <li key={i}>
              <button
                className={"mc-diag-option" + (isSelected ? " is-selected" : "")}
                onClick={() => onChoose(step.key, o.value)}>
                
                <span className="letter">{letter}</span>
                <span className="body">
                  <span className="label">{o.label}</span>
                </span>
                <span className="arr">→</span>
              </button>
            </li>);

        })}
      </ul>

      {step.insight &&
      <div className="mc-diag-insight">
          <span className="ic" aria-hidden="true">↗</span>
          <div>
            {step.insightTitle && <p className="mc-diag-insight-title">{step.insightTitle}</p>}
            <p>{step.insight}</p>
          </div>
        </div>
      }

      {onBack &&
      <button className="mc-diag-back" onClick={onBack}>← Previous question</button>
      }
    </div>);

};

// -------------------- RESULTS VIEW (Step 8) --------------------
const ResultsView = ({
  answers, fit, fitCopy, targetCases, conversion, fee, monthlyCapacity,
  estRevenue, dbSize, reactivationCases, reactivationRevenue,
  fmt, contact, setContact, onSubmit, onBack
}) => {
  const set = (k) => (e) => setContact({ ...contact, [k]: e.target.value });
  const valid =
    contact.name.trim() &&
    contact.practice.trim() &&
    contact.city.trim() &&
    contact.focus.trim() &&
    /.+@.+\..+/.test(contact.email);

  return (
    <div className="mc-diag-step">
      <div className="mc-diag-overline">Your private review · {fit === "strong" ? "Strong fit for reactivation" : fit === "medium" ? "Worth a diagnosis" : fit === "nodb" ? "Not the right service yet" : "Not the right moment"}</div>
      <h2 className="mc-diag-q">{fitCopy.title}</h2>
      <p className="mc-diag-q-sub">{fitCopy.body}</p>

      {/* PROJECTION */}
      <div className="mc-diag-projection">
        <div className="head">
          <span className="ic">↗</span>
          <span>Indicative commercial opportunity</span>
        </div>
        <div className="row"><span>Desired new cases / month</span><strong>{targetCases}</strong></div>
        <div className="row"><span>Current consultation conversion</span><strong>{Math.round(conversion * 100)}%</strong></div>
        <div className="row"><span>Average case fee</span><strong>{fmt(fee)}</strong></div>
        <div className="row"><span>Monthly consultation capacity</span><strong>{monthlyCapacity}</strong></div>
        {dbSize > 0 &&
          <div className="row"><span>Inactive leads in database</span><strong>{dbSize.toLocaleString("fr-CH").replace(/,/g, "\u202f")}</strong></div>
        }
        {dbSize > 0 &&
          <div className="row total"><span>Reactivation potential <span style={{ opacity: 0.6 }}>(≈8% of database)</span></span><strong className="rev">{fmt(reactivationRevenue)}</strong></div>
        }
        <div className="row total"><span>Indicative new revenue / month</span><strong className="rev">{fmt(estRevenue)}</strong></div>
        <div className="row total"><span>Indicative new revenue / year</span><strong className="rev">{fmt(estRevenue * 12)}</strong></div>
        <div className="foot">Indicative only. The system Malca builds is sized to your specialty, market, and team capacity.</div>
      </div>

      {/* RESULT CARDS */}
      <div className="mc-diag-results">
        <ResultCard
          eyebrow="01 / Where we would look first"
          title="Where attention has already been created — and what happened next."
          intro="The first question is not “how do we get more attention?” It is: where did existing attention go?"
          items={[
            "Past enquiries",
            "Unconverted consultations",
            "Inactive treatment plans",
            "Existing patient database",
            "Booking path",
            "Consultation conversion",
            "Follow-up rhythm",
            "Team ownership"]}
          insight="A strong practice can have real demand and still lose treatment revenue if the path from interest to decision is not structured clearly." />

        <ResultCard
          eyebrow="02 / Your reactivation opportunity"
          title="Whether there is value already sitting inside the practice."
          intro="Your existing database can show how much treatment interest has already been created and not converted."
          items={[
            "Database size",
            "Type of enquiries",
            "Treatment interest",
            "Time since enquiry",
            "Case value",
            "Consultation capacity",
            "Conversion rate",
            "Follow-up ownership"]}
          insight="Reactivation is not “chasing old leads.” Done properly, it is a structured way to return to patients who already expressed interest and guide them back into a clear next step." />

        <ResultCard
          eyebrow="03 / Your conversion opportunity"
          title="What happens inside and after the consultation."
          intro="If patients are already coming in, the next question is how they move from interest to decision."
          items={[
            "Consultation structure",
            "Treatment explanation",
            "Objection handling",
            "Financing clarity",
            "Decision timeline",
            "Follow-up protocol",
            "Who owns the next step"]}
          insight="The practice does not only grow by increasing demand. It grows when more of the right patients move through the existing journey with clarity and confidence." />

        <ResultCard
          eyebrow="04 / Your capacity opportunity"
          title="What the practice can actually deliver."
          intro="Growth should be sized around what the team and the chair time can support."
          items={[
            "Weekly consultation slots",
            "Treatment coordinator availability",
            "Owner involvement",
            "Team follow-up capacity",
            "Chair time",
            "Patient experience",
            "Operational load"]}
          insight="A commercial system should make the practice feel more controlled, not more stretched." />

        <ResultCard
          eyebrow="05 / This is likely a strong fit"
          title="If your practice has:"
          items={[
            "Real clinical expertise",
            "Premium treatment value",
            "Strong patient outcomes",
            "Existing enquiries or patient history",
            "Unconverted consultations or paused treatment plans",
            "A team member who can execute",
            "An owner ready to stop carrying the commercial system alone"]} />

        <ResultCard
          eyebrow="06 / This is probably not the right fit"
          title="If you are looking for:"
          negative
          items={[
            "Quick leads",
            "Social media management",
            "Discount campaigns",
            "Cosmetic marketing",
            "A generic audit",
            "Free pilots",
            "A supplier to chase",
            "More dependency on the owner"]} />
      </div>

      {/* BOOKING */}
      <div className="mc-diag-booking">
        <div className="mc-diag-overline">Request your private practice review</div>
        <h3 className="mc-diag-reasons-h">
          Request your <em>private practice review</em>.
        </h3>

        <div className="mc-diag-tags">
          <span className="tag is-light"><span className="ic">◷</span> 30-minute in-person meeting</span>
          <span className="tag"><span className="ic">◐</span> Prepared on your practice</span>
          <span className="tag"><span className="ic">✦</span> No generic audit</span>
        </div>

        <p className="mc-diag-q-sub" style={{ marginTop: 20 }}>
          We review your patient journey, database opportunity, and commercial system before the meeting — so the conversation is specific, practical, and worth your time.
        </p>

        <aside className="mc-diag-exclusivity">
          <div className="head">
            <span className="ic">🔒︎</span>
            <span>One engagement per catchment area</span>
          </div>
          <p>
            To protect the practices we work with, we sign an exclusivity clause for your catchment area. Once a practice in your area is onboarded, we will not take on a direct competitor.
          </p>
        </aside>

        <form className="mc-diag-form" onSubmit={onSubmit}>
          <div className="field">
            <label>Your name</label>
            <div className="ipt"><span className="ic">◐</span><input required value={contact.name} onChange={set("name")} placeholder="Dr. Jane Smith" /></div>
          </div>
          <div className="field">
            <label>Email address</label>
            <div className="ipt"><span className="ic">✉</span><input type="email" required value={contact.email} onChange={set("email")} placeholder="jane@yourpractice.ch" /></div>
          </div>
          <div className="field">
            <label>Practice name</label>
            <div className="ipt"><span className="ic">⌂</span><input required value={contact.practice} onChange={set("practice")} placeholder="Cabinet d’orthodontie · Genève" /></div>
          </div>
          <div className="field">
            <label>Practice website <span style={{ color: "var(--mc-stone)", fontWeight: 400 }}>(optional)</span></label>
            <div className="ipt"><span className="ic">⌬</span><input type="url" value={contact.website} onChange={set("website")} placeholder="https://yourpractice.ch" /></div>
          </div>
          <div className="field">
            <label>City / location</label>
            <div className="ipt"><span className="ic">◎</span><input required value={contact.city} onChange={set("city")} placeholder="Geneva, Switzerland" /></div>
          </div>
          <div className="field">
            <label>Main treatment focus</label>
            <div className="ipt"><span className="ic">✧</span><input required value={contact.focus} onChange={set("focus")} placeholder="Invisalign / orthodontics" /></div>
          </div>

          <button className="mc-btn mc-btn-primary mc-diag-submit" type="submit" disabled={!valid}>
            Request my practice review
            <span className="arr">→</span>
          </button>
          <p className="mc-diag-foot">
            Limited engagements per year · Reviewed personally
          </p>
        </form>
      </div>

      {onBack &&
      <button className="mc-diag-back" onClick={onBack}>← Previous question</button>
      }
    </div>);

};

const ResultCard = ({ eyebrow, title, intro, items, insight, negative }) =>
<div className={"mc-diag-resultcard" + (negative ? " is-negative" : "")}>
    <div className="mc-diag-resultcard-eyebrow">{eyebrow}</div>
    <h4 className="mc-diag-resultcard-title">{title}</h4>
    {intro && <p className="mc-diag-resultcard-intro">{intro}</p>}
    <ul className="mc-diag-resultcard-list">
      {items.map((it, i) =>
      <li key={i}>
          <span className="mk" aria-hidden="true">{negative ? "×" : "·"}</span>
          <span>{it}</span>
        </li>
      )}
    </ul>
    {insight &&
    <p className="mc-diag-resultcard-insight"><em>{insight}</em></p>
    }
  </div>;

// -------------------- SENT VIEW --------------------
const SentView = ({ estRevenue, targetCases, fmt, onNavigate }) =>
<div className="mc-diag-step mc-diag-sent">
    <div className="mc-diag-overline">Received</div>
    <h2 className="mc-diag-q">Your submission has <em>been received</em>.</h2>
    <p className="mc-diag-q-sub">
      If a Malca engagement is the right move for your practice, you will be invited to a private 30-minute conversation within two working days.
    </p>
    <div className="mc-diag-summary">
      <div className="row"><span>Indicative new revenue / month</span><strong>{fmt(estRevenue)}</strong></div>
      <div className="row"><span>Indicative new revenue / year</span><strong>{fmt(estRevenue * 12)}</strong></div>
      <div className="row"><span>Indicative new cases / month</span><strong>{targetCases}</strong></div>
      <div className="foot">These are conservative projections, sized to your stated capacity.</div>
    </div>
    <div className="mc-diag-cta-row">
      <button className="mc-btn mc-btn-secondary" onClick={() => onNavigate("home")}>Back to home</button>
      <a className="mc-btn mc-btn-text" href="mailto:hello@malcaconsulting.com">hello@malcaconsulting.com</a>
    </div>
  </div>;


Object.assign(window, { DiagnosticPage });
