CleanRhizo
#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 700
#| viewerWidth: "100%"

suppressPackageStartupMessages(library(shiny))
suppressPackageStartupMessages(library(bslib))

# ── Colonne di default da mantenere ──────────────────────────────────────────
DEFAULT_KEEP <- c(
  "SampleId", "Analysis Date Time",
  "Length(cm)", "SurfArea(cm2)",
  "AvgDiam(mm)", "RootVolume(cm3)",
  "Tips", "Forks", "Crossings",
  "source_file"  # solo con più file: da quale file viene ogni campione
)

# ── Rinomina fissa ────────────────────────────────────────────────────────────
COL_RENAME <- c(
  "Analysis Date Time" = "datetime"
)

# ── Dati di esempio sintetici, non misure reali ──────────────────────────────
# Stesso contenuto di tests/data/example_winrhizo.txt (verificato dai test).
EXAMPLE_WINRHIZO <- c(
  "RHIZO 2021a\tAnalysis Date Time\tLength(cm)\tProjArea(cm2)\tSurfArea(cm2)\tAvgDiam(mm)\tRootVolume(cm3)\tTips\tForks\tCrossings",
  "COLOR\tValue\tValue\tValue\tValue\tValue\tValue\tValue\tValue\tValue",
  "LINK\tValue\tValue\tValue\tValue\tValue\tValue\tValue\tValue\tValue",
  "DEV\tValue\tValue\tValue\tValue\tValue\tValue\tValue\tValue\tValue",
  "AXIS\tValue\tValue\tValue\tValue\tValue\tValue\tValue\tValue\tValue",
  "CTRL.1.1\t2026-03-11 10:01:00\t104.750\t9.428\t29.644\t0.830\t0.629\t209\t314\t20",
  "CTRL.1.2\t2026-03-11 10:02:00\t106.250\t9.562\t30.069\t0.830\t0.638\t212\t318\t21",
  "CTRL.2.1\t2026-03-12 10:03:00\t108.000\t9.720\t30.564\t0.840\t0.648\t216\t324\t21",
  "CTRL.2.2\t2026-03-12 10:04:00\t109.500\t9.855\t30.988\t0.840\t0.657\t219\t328\t21",
  "CTRL.3.1\t2026-03-13 10:05:00\t111.250\t10.012\t31.484\t0.850\t0.667\t222\t333\t22",
  "CTRL.3.2\t2026-03-13 10:06:00\t112.750\t10.147\t31.908\t0.850\t0.676\t225\t338\t22",
  "100_PPM_UREA.1.1\t2026-03-11 10:07:00\t144.750\t13.027\t40.964\t0.830\t0.869\t289\t434\t28",
  "100_PPM_UREA.1.2\t2026-03-11 10:08:00\t146.250\t13.162\t41.389\t0.830\t0.878\t292\t438\t29",
  "100_PPM_UREA.2.1\t2026-03-12 10:09:00\t148.000\t13.320\t41.884\t0.840\t0.888\t296\t444\t29",
  "100_PPM_UREA.2.2\t2026-03-12 10:10:00\t149.500\t13.455\t42.308\t0.840\t0.897\t299\t448\t29",
  "100_PPM_UREA.3.1\t2026-03-13 10:11:00\t151.250\t13.612\t42.804\t0.850\t0.907\t302\t453\t30",
  "100_PPM_UREA.3.2\t2026-03-13 10:12:00\t152.750\t13.747\t43.228\t0.850\t0.916\t305\t458\t30",
  "100_PPM_NH4.1.1\t2026-03-11 10:13:00\t88.400\t8.310\t26.105\t0.940\t0.613\t141\t212\t13",
  "100_PPM_NH4.1.2\t2026-03-11 10:14:00\t92.100\t8.565\t26.909\t0.930\t0.626\t147\t221\t14",
  "100_PPM_NH4.2.1\t2026-03-12 10:15:00\t96.700\t9.283\t29.164\t0.960\t0.700\t155\t232\t15",
  "100_PPM_NH4.2.2\t2026-03-12 10:16:00\t101.300\t9.623\t30.233\t0.950\t0.718\t162\t243\t15",
  "100_PPM_NH4.3.1\t2026-03-13 10:17:00\t84.900\t7.811\t24.538\t0.920\t0.564\t136\t204\t13",
  "100_PPM_NH4.3.2\t2026-03-13 10:18:00\t90.600\t8.426\t26.470\t0.930\t0.615\t145\t217\t14",
  "100_PPM_NO3.1.1\t2026-03-11 10:19:00\t171.200\t12.669\t39.800\t0.740\t0.736\t411\t582\t41",
  "100_PPM_NO3.1.2\t2026-03-11 10:20:00\t165.800\t12.435\t39.066\t0.750\t0.732\t398\t564\t40",
  "100_PPM_NO3.2.1\t2026-03-12 10:21:00\t182.600\t13.147\t41.303\t0.720\t0.743\t438\t621\t44",
  "100_PPM_NO3.2.2\t2026-03-12 10:22:00\t189.400\t13.826\t43.436\t0.730\t0.793\t455\t644\t45",
  "100_PPM_NO3.3.1\t2026-03-13 10:23:00\t158.300\t12.031\t37.796\t0.760\t0.718\t380\t538\t38",
  "100_PPM_NO3.3.2\t2026-03-13 10:24:00\t163.700\t12.277\t38.571\t0.750\t0.723\t393\t557\t39"
)
EXAMPLE_SCHEME <- 2  # i campioni di esempio seguono Trattamento.Vaso.Pianta

# ── Dizionario UI (it, en, es, fr) ────────────────────────────────────────────────────
TR <- list(
  it = list(
    app_subtitle     = "Pulizia dati di morfologia radicale da",
    app_descr        = "Software per l'analisi dell'architettura radicale da immagini scansionate — Regent Instruments.",
    privacy_title    = "Il tuo file resta nel browser",
    privacy_body     = "Questa applicazione gira interamente nel tuo browser grazie a WebR: il file che carichi viene elaborato solo sul tuo dispositivo e non viene mai inviato a un server. La connessione serve solo per aprire la pagina; dopo, l'app funziona anche offline. Al primo avvio potrebbe essere necessario qualche secondo per il caricamento dell'ambiente R. Come ogni pagina web, viene fornita da un servizio di hosting, che riceve dati tecnici come l'indirizzo IP. Google Analytics viene caricato solo con il tuo consenso, per raccogliere statistiche di utilizzo che non includono mai il tuo file. Le preferenze (lingua, palette, schema dei nomi e separatore CSV) vengono salvate solo in questo browser, mai il contenuto del file.",
    guide_title    = "📋 Come nominare i campioni in WinRhizo",
    guide_intro    = "Per evitare ambiguità in fase di analisi, conviene definire una convenzione di denominazione prima di iniziare la scansione. Questa app riconosce automaticamente due schemi:",
    guide_case1_title = "Caso semplice — una sola replica per campione",
    guide_case1_body  = "Usa il formato TRATTAMENTO_replica, con un underscore prima del numero progressivo.",
    guide_case1_ex1   = "TRATTAMENTO_1, TRATTAMENTO_2, TRATTAMENTO_3 …",
    guide_case2_title = "Caso con due livelli — replica biologica e tecnica",
    guide_case2_body  = "Se ogni vaso contiene più piante (o più sotto-campioni), conviene distinguere tra replica biologica (il vaso, cioè un individuo o gruppo indipendente) e replica tecnica (la singola pianta o misura ripetuta all'interno dello stesso vaso). Usa TRATTAMENTO.vaso.pianta, con un punto prima dei due numeri:",
    guide_case2_ex1   = "TRATTAMENTO.1.1, TRATTAMENTO.1.2 → vaso 1, piante 1 e 2",
    guide_case2_ex2   = "TRATTAMENTO.2.1, TRATTAMENTO.2.2 → vaso 2, piante 1 e 2",
    guide_why_title   = "Perché il punto e non l'underscore per vaso/pianta?",
    guide_why_body    = "Quando il nome del trattamento è composto da più parole unite da underscore (es. 100_PPM_UREA), l'app non ha modo di sapere a colpo d'occhio dove finisce il nome e dove iniziano i numeri di vaso e pianta: tutti gli underscore sembrano uguali. Usando il punto solo per introdurre i numeri di replica, il confine tra nome e numeri diventa sempre riconoscibile, qualunque sia la complessità del nome del trattamento.",
    guide_why_ex1     = "100_PPM_UREA_1_2 → ambiguo: l'ultimo '_1' potrebbe far parte del nome o essere il vaso",
    guide_why_ex2     = "100_PPM_UREA.1.2 → chiaro: trattamento 100_PPM_UREA, vaso 1, pianta 2",
    guide_collapse    = "Comprimi guida",
    guide_expand      = "Mostra guida",
    status_waiting   = "In attesa",
    status_loaded    = "✓ File caricato",
    status_clean     = "✓ File pulito",
    status_trt       = "✓ Trattamenti aggiunti",
    status_final     = "✓ File finale pronto",
    status_error     = "✗ Errore",
    step1            = "1 — Carica il file",
    file_placeholder = "Seleziona uno o più file .txt esportati da WinRhizo…",
    file_btn         = "Sfoglia",
    example_btn      = "Prova con dati di esempio",
    example_note     = "Dati di esempio sintetici, non misure reali.",
    file_info        = function(nr, nc) paste0(nr, " campioni · ", nc, " colonne rilevate"),
    files_merged     = function(n) paste0(n, " file uniti"),
    files_cols_warning = "I file non hanno tutti le stesse colonne. Restano vuote per i campioni dei file in cui mancano:",
    step2            = "2 — Seleziona le colonne da mantenere",
    sel_all          = "Seleziona tutte",
    desel_all        = "Deseleziona tutte",
    derived_note     = "Le colonne tratteggiate sono calcolate dall'app: TipsPerLength = Tips / Length(cm), ForksPerLength = Forks / Length(cm).",
    col_meta         = "colonne selezionate",
    col_of           = "di",
    err_no_cols      = "Seleziona almeno una colonna prima di generare il file pulito.",
    step3            = "3 — Genera il file pulito",
    btn_clean        = "Pulisci",
    btn_dl_clean     = "Scarica CSV pulito",
    csv_sep_lbl      = "Separatore dei file CSV:",
    csv_sep_semicolon = "; punto e virgola",
    csv_sep_comma    = ", virgola",
    csv_sep_hint     = "Vale per tutti i CSV scaricati. Excel in italiano usa ';', Excel in inglese ','.",
    summary          = "Riepilogo",
    renamed_lbl      = "Colonne rinominate automaticamente:",
    stat_samples     = "campioni",
    stat_cols        = "colonne",
    stat_file        = "nome file",
    preview8         = "Anteprima dati",
    step4            = "4 — Assegna i trattamenti ai campioni",
    trt_hint         = "WinRhizo codifica il trattamento nel nome del campione. Scegli lo schema corretto in base al tuo setup sperimentale, poi verifica o modifica i trattamenti personalizzati.",
    trt_scheme_lbl   = "Schema del nome campione:",
    trt_scheme_1     = "Trattamento_Replica",
    trt_scheme_1_sub = "es. XYZ_3 → trattamento XYZ, replica 3",
    trt_scheme_2     = "Trattamento.Vaso.Pianta",
    trt_scheme_2_sub = "es. X_Y_Z.1.2 → trattamento X_Y_Z, vaso 1, pianta 2",
    trt_scheme_3     = "Manuale",
    trt_scheme_3_sub = "assegna tu il ruolo di ogni parte del nome",
    trt_manual_lbl   = "Assegna un ruolo a ciascuna parte del SampleId:",
    trt_manual_hint  = "Basato sul primo campione del file. Riconosce underscore, punto e spazio come separatori. I segmenti consecutivi con lo stesso ruolo 'Trattamento' vengono uniti automaticamente.",
    trt_manual_role_treatment = "Trattamento",
    trt_manual_role_pot       = "Vaso",
    trt_manual_role_plant     = "Pianta",
    trt_manual_role_ignore    = "Ignora",
    trt_manual_mismatch = "Attenzione: alcuni SampleId hanno una struttura diversa dal campione di riferimento e non sono stati interpretati correttamente (mostrati con il nome originale come trattamento).",
    trt_scheme_mismatch = "Attenzione: alcuni SampleId non rispettano lo schema scelto. Il nome originale è usato come trattamento e le repliche restano vuote.",
    trt_col_sample   = "SampleId",
    trt_col_detected = "Trattamento rilevato",
    trt_col_replica  = "Replica",
    trt_col_vaso     = "Vaso (rep. biologica)",
    trt_col_pianta   = "Pianta (rep. tecnica)",
    trt_col_custom   = "Trattamento personalizzato",
    btn_trt          = "Aggiungi colonna trattamento e replica",
    trt_preview      = "Anteprima con trattamenti",
    btn_dl_trt       = "Scarica CSV con trattamenti",
    step_qc          = "5 — Controllo qualità",
    qc_hint          = "Controlli automatici: scansioni duplicate, valori mancanti o a zero, possibili outlier per trattamento (oltre 5 MAD dalla mediana su scala logaritmica, per lunghezza, superficie, diametro e volume, con almeno 5 campioni) e repliche sbilanciate. I campioni esclusi non entrano nel file finale, nella tabella e nel grafico.",
    qc_stat_flagged  = "da controllare",
    qc_stat_excluded = "esclusi",
    qc_none          = "Nessuna segnalazione: non risultano problemi evidenti.",
    qc_balance_lbl   = "Repliche non bilanciate",
    qc_units_pot     = "vasi per trattamento",
    qc_units         = "repliche per trattamento",
    qc_single        = "Con una sola replica SD e SE non sono calcolabili.",
    qc_drop_dups     = "Escludi le scansioni duplicate più vecchie",
    qc_dups_by_time  = "Per ogni duplicato resta la scansione più recente, in base a data e ora.",
    qc_dups_by_order = "Data e ora non leggibili: per ogni duplicato resta l'ultima scansione del file.",
    qc_show_all_label = "Mostra tutti i campioni",
    qc_show_all_sub  = "Per escludere anche campioni senza segnalazioni",
    qc_col_include   = "Includi",
    qc_col_issues    = "Segnalazioni",
    qc_issue_duplicate = "Duplicato",
    qc_issue_missing = "Mancante",
    qc_issue_zero    = "Zero",
    qc_issue_outlier = "Possibile outlier",
    qc_reset         = "Includi di nuovo tutti i campioni",
    qc_regen_note    = "Dopo ogni modifica, rigenera il file finale al passaggio 6.",
    btn_dl_qc        = "Scarica report QC (CSV)",
    qc_all_excluded  = "Tutti i campioni sono esclusi: includine almeno uno al passaggio 5.",
    step_final       = "6 — Formato finale e download",
    pivot_label      = "Trasponi parametri in formato long",
    pivot_sub        = "Le colonne numeriche verranno unite in una colonna 'parameter' con i valori in 'value'",
    btn_final        = "Genera file finale",
    btn_dl_final     = "Scarica CSV finale",
    stat_rows        = "righe",
    stat_format      = "formato",
    stat_excluded    = "esclusi (QC)",
    final_preview    = "Anteprima file finale",
    step_summary     = "7 — Tabella riassuntiva",
    summary_hint     = "Media, deviazione standard (SD), errore standard (SE) e n per trattamento, per tutti i parametri numerici. I trattamenti seguono l'ordine scelto al passaggio 8.",
    summary_pot_note = "Schema Vaso/Pianta: le piante dello stesso vaso (repliche tecniche) vengono prima mediate per vaso. Media, SD, SE e n sono calcolati tra vasi (repliche biologiche).",
    btn_dl_summary   = "Scarica tabella CSV",
    step_chart       = "8 — Grafico esplorativo",
    chart_param_lbl  = "Seleziona i parametri da visualizzare:",
    chart_hint       = "Solo a scopo di controllo qualità rapido — non sostituisce l'analisi statistica.",
    chart_pot_note   = "Schema Vaso/Pianta: le piante dello stesso vaso (repliche tecniche) vengono prima mediate per vaso. Media, SE, box, punti e n sono calcolati tra vasi (repliche biologiche).",
    chart_type_lbl   = "Tipo di grafico:",
    chart_type_bar   = "Barre",
    chart_type_bar_sub = "media ± SE",
    chart_type_box   = "Boxplot",
    chart_type_box_sub = "mediana, quartili, baffi",
    chart_type_points = "Punti",
    chart_type_points_sub = "ogni replica, media ± SE",
    palette_lbl      = "Palette di colori:",
    palette_npg_sub  = "colori vivaci, predefinita",
    palette_okabe_sub = "adatta al daltonismo",
    palette_gray     = "Scala di grigi",
    palette_gray_sub = "per la stampa in bianco e nero",
    order_lbl        = "Ordine dei trattamenti:",
    order_hint       = "Il primo trattamento è il riferimento della vista % del controllo.",
    order_left       = "Sposta a sinistra",
    order_right      = "Sposta a destra",
    pct_label        = "Mostra come % del controllo",
    pct_sub          = "Ogni valore è diviso per la media del primo trattamento dell'elenco (= 100%)",
    btn_chart        = "Genera grafico",
    btn_dl_png       = "Scarica PNG",
    btn_dl_pdf       = "Scarica PDF",
    btn_dl_svg       = "Scarica SVG",
    err_export       = "Questo formato non è disponibile in questo browser.",
    btn_clear        = "Cancella grafico",
    chart_no_params  = "Nessun parametro numerico disponibile nel file finale.",
    chart_ylab       = "Valore medio",
    chart_ylab_value = "Valore",
    chart_ylab_pct   = "% del controllo",
    chart_no_ref     = "Media di riferimento non disponibile",
    jitter_label     = "Mostra punti individuali (jitter)",
    jitter_sub       = "Visualizza ogni singola misura come puntino, utile per individuare outlier o valutare la distribuzione",
    credits          = list(
      pre  = "Applicazione creata da ",
      bug  = " · Segnala problemi su ",
      or   = " o via ",
      mail = "mail"
    )
  ),
  en = list(
    app_subtitle     = "Root morphology data cleaning from",
    app_descr        = "Software for root architecture analysis from scanned images — Regent Instruments.",
    privacy_title    = "Your file stays in your browser",
    privacy_body     = "This application runs entirely in your browser using WebR: the file you load is processed only on your device and is never sent to a server. An internet connection is needed only to open the page; after that, the app also works offline. On the first load, a few seconds may be needed to initialise the R environment. Like any web page, it is delivered by a hosting service, which receives technical data such as your IP address. Google Analytics is loaded only with your consent, to collect usage statistics that never include your file. Preferences (language, palette, naming scheme and CSV separator) are saved only in this browser, never the content of your file.",
    guide_title    = "📋 How to name samples in WinRhizo",
    guide_intro    = "To avoid ambiguity at analysis time, it helps to define a naming convention before you start scanning. This app automatically recognises two schemes:",
    guide_case1_title = "Simple case — a single replicate per sample",
    guide_case1_body  = "Use the format TREATMENT_replicate, with an underscore before the sequential number.",
    guide_case1_ex1   = "TREATMENT_1, TREATMENT_2, TREATMENT_3 …",
    guide_case2_title = "Two-level case — biological and technical replicate",
    guide_case2_body  = "If each pot contains multiple plants (or multiple sub-samples), it helps to distinguish between the biological replicate (the pot, i.e. an independent individual or group) and the technical replicate (the single plant or repeated measurement within the same pot). Use TREATMENT.pot.plant, with a dot before the two numbers:",
    guide_case2_ex1   = "TREATMENT.1.1, TREATMENT.1.2 → pot 1, plants 1 and 2",
    guide_case2_ex2   = "TREATMENT.2.1, TREATMENT.2.2 → pot 2, plants 1 and 2",
    guide_why_title   = "Why a dot instead of an underscore for pot/plant?",
    guide_why_body    = "When the treatment name is made up of several words joined by underscores (e.g. 100_PPM_UREA), the app has no way to tell at a glance where the name ends and where the pot and plant numbers begin: every underscore looks the same. By using the dot only to introduce the replicate numbers, the boundary between name and numbers stays recognisable, no matter how complex the treatment name is.",
    guide_why_ex1     = "100_PPM_UREA_1_2 → ambiguous: the last '_1' could be part of the name or the pot",
    guide_why_ex2     = "100_PPM_UREA.1.2 → clear: treatment 100_PPM_UREA, pot 1, plant 2",
    guide_collapse    = "Collapse guide",
    guide_expand      = "Show guide",
    status_waiting   = "Waiting",
    status_loaded    = "✓ File loaded",
    status_clean     = "✓ File cleaned",
    status_trt       = "✓ Treatments added",
    status_final     = "✓ Final file ready",
    status_error     = "✗ Error",
    step1            = "1 — Load file",
    file_placeholder = "Select one or more .txt files exported from WinRhizo…",
    file_btn         = "Browse",
    example_btn      = "Try with example data",
    example_note     = "Synthetic example data, not real measurements.",
    file_info        = function(nr, nc) paste0(nr, " samples · ", nc, " columns detected"),
    files_merged     = function(n) paste0(n, " files merged"),
    files_cols_warning = "The files do not all have the same columns. They are left empty for samples from files that lack them:",
    step2            = "2 — Select columns to keep",
    sel_all          = "Select all",
    desel_all        = "Deselect all",
    derived_note     = "Dashed columns are computed by the app: TipsPerLength = Tips / Length(cm), ForksPerLength = Forks / Length(cm).",
    col_meta         = "columns selected",
    col_of           = "of",
    err_no_cols      = "Select at least one column before generating the cleaned file.",
    step3            = "3 — Generate cleaned file",
    btn_clean        = "Clean",
    btn_dl_clean     = "Download cleaned CSV",
    csv_sep_lbl      = "CSV separator:",
    csv_sep_semicolon = "; semicolon",
    csv_sep_comma    = ", comma",
    csv_sep_hint     = "Applies to every CSV you download. Excel in many European languages uses ';', English Excel uses ','.",
    summary          = "Summary",
    renamed_lbl      = "Automatically renamed columns:",
    stat_samples     = "samples",
    stat_cols        = "columns",
    stat_file        = "file name",
    preview8         = "Data preview",
    step4            = "4 — Assign treatments to samples",
    trt_hint         = "WinRhizo encodes the treatment in the sample name. Pick the scheme that matches your experimental setup, then review or override the custom treatment for each sample.",
    trt_scheme_lbl   = "Sample name scheme:",
    trt_scheme_1     = "Treatment_Replicate",
    trt_scheme_1_sub = "e.g. XYZ_3 → treatment XYZ, replicate 3",
    trt_scheme_2     = "Treatment.Pot.Plant",
    trt_scheme_2_sub = "e.g. X_Y_Z.1.2 → treatment X_Y_Z, pot 1, plant 2",
    trt_scheme_3     = "Manual",
    trt_scheme_3_sub = "assign the role of each name part yourself",
    trt_manual_lbl   = "Assign a role to each part of the SampleId:",
    trt_manual_hint  = "Based on the first sample in the file. Recognizes underscore, dot, and space as separators. Consecutive segments with the same 'Treatment' role are merged automatically.",
    trt_manual_role_treatment = "Treatment",
    trt_manual_role_pot       = "Pot",
    trt_manual_role_plant     = "Plant",
    trt_manual_role_ignore    = "Ignore",
    trt_manual_mismatch = "Warning: some SampleIds have a different structure than the reference sample and were not parsed correctly (shown with the original name as treatment).",
    trt_scheme_mismatch = "Warning: some SampleIds do not match the selected scheme. The original name is used as treatment and the replicates are left empty.",
    trt_col_sample   = "SampleId",
    trt_col_detected = "Detected treatment",
    trt_col_replica  = "Replicate",
    trt_col_vaso     = "Pot (biological rep.)",
    trt_col_pianta   = "Plant (technical rep.)",
    trt_col_custom   = "Custom treatment",
    btn_trt          = "Add treatment & replicate columns",
    trt_preview      = "Preview with treatments",
    btn_dl_trt       = "Download CSV with treatments",
    step_qc          = "5 — Quality control",
    qc_hint          = "Automatic checks: duplicate scans, missing or zero values, possible outliers per treatment (more than 5 MAD from the median on a log scale, for length, surface area, diameter and volume, with at least 5 samples) and unbalanced replicates. Excluded samples are left out of the final file, the table and the chart.",
    qc_stat_flagged  = "to check",
    qc_stat_excluded = "excluded",
    qc_none          = "No flags: no obvious problems found.",
    qc_balance_lbl   = "Unbalanced replicates",
    qc_units_pot     = "pots per treatment",
    qc_units         = "replicates per treatment",
    qc_single        = "With a single replicate SD and SE cannot be computed.",
    qc_drop_dups     = "Exclude older duplicate scans",
    qc_dups_by_time  = "For each duplicate the most recent scan is kept, based on date and time.",
    qc_dups_by_order = "Date and time not readable: for each duplicate the last scan in the file is kept.",
    qc_show_all_label = "Show all samples",
    qc_show_all_sub  = "To also exclude samples without flags",
    qc_col_include   = "Include",
    qc_col_issues    = "Flags",
    qc_issue_duplicate = "Duplicate",
    qc_issue_missing = "Missing",
    qc_issue_zero    = "Zero",
    qc_issue_outlier = "Possible outlier",
    qc_reset         = "Include all samples again",
    qc_regen_note    = "After any change, regenerate the final file in step 6.",
    btn_dl_qc        = "Download QC report (CSV)",
    qc_all_excluded  = "All samples are excluded: include at least one in step 5.",
    step_final       = "6 — Final format and download",
    pivot_label      = "Transpose parameters to long format",
    pivot_sub        = "Numeric columns will be merged into a 'parameter' column with values in 'value'",
    btn_final        = "Generate final file",
    btn_dl_final     = "Download final CSV",
    stat_rows        = "rows",
    stat_format      = "format",
    stat_excluded    = "excluded (QC)",
    final_preview    = "Final file preview",
    step_summary     = "7 — Summary table",
    summary_hint     = "Mean, standard deviation (SD), standard error (SE) and n per treatment, for all numeric parameters. Treatments follow the order chosen in step 8.",
    summary_pot_note = "Pot/Plant scheme: plants from the same pot (technical replicates) are first averaged per pot. Mean, SD, SE and n are computed across pots (biological replicates).",
    btn_dl_summary   = "Download table CSV",
    step_chart       = "8 — Exploratory chart",
    chart_param_lbl  = "Select parameters to display:",
    chart_hint       = "For quick quality control only — not a substitute for proper statistical analysis.",
    chart_pot_note   = "Pot/Plant scheme: plants from the same pot (technical replicates) are first averaged per pot. Mean, SE, boxes, points and n are computed across pots (biological replicates).",
    chart_type_lbl   = "Chart type:",
    chart_type_bar   = "Bars",
    chart_type_bar_sub = "mean ± SE",
    chart_type_box   = "Boxplot",
    chart_type_box_sub = "median, quartiles, whiskers",
    chart_type_points = "Points",
    chart_type_points_sub = "each replicate, mean ± SE",
    palette_lbl      = "Color palette:",
    palette_npg_sub  = "vivid colors, default",
    palette_okabe_sub = "colorblind-friendly",
    palette_gray     = "Grayscale",
    palette_gray_sub = "for black-and-white printing",
    order_lbl        = "Treatment order:",
    order_hint       = "The first treatment is the reference for the % of control view.",
    order_left       = "Move left",
    order_right      = "Move right",
    pct_label        = "Show as % of control",
    pct_sub          = "Each value is divided by the mean of the first treatment in the list (= 100%)",
    btn_chart        = "Generate chart",
    btn_dl_png       = "Download PNG",
    btn_dl_pdf       = "Download PDF",
    btn_dl_svg       = "Download SVG",
    err_export       = "This format is not available in this browser.",
    btn_clear        = "Clear chart",
    chart_no_params  = "No numeric parameters available in the final file.",
    chart_ylab       = "Mean value",
    chart_ylab_value = "Value",
    chart_ylab_pct   = "% of control",
    chart_no_ref     = "Reference mean not available",
    jitter_label     = "Show individual data points (jitter)",
    jitter_sub       = "Overlay each measurement as a dot, useful to spot outliers or assess distribution",
    credits          = list(
      pre  = "Application developed by ",
      bug  = " · Report issues on ",
      or   = " or via ",
      mail = "email"
    )
  ),
  es = list(
    app_subtitle     = "Limpieza de datos de morfología radicular desde",
    app_descr        = "Software para el análisis de la arquitectura radicular a partir de imágenes escaneadas — Regent Instruments.",
    privacy_title    = "Su archivo permanece en el navegador",
    privacy_body     = "Esta aplicación se ejecuta completamente en su navegador gracias a WebR: el archivo que cargue se procesa únicamente en su dispositivo y nunca se envía a un servidor. Solo se necesita conexión para abrir la página; después, la aplicación también funciona sin conexión. En el primer inicio puede ser necesario esperar unos segundos para cargar el entorno R. Como cualquier página web, la proporciona un servicio de alojamiento, que recibe datos técnicos como la dirección IP. Google Analytics solo se carga con su consentimiento, para recopilar estadísticas de uso que nunca incluyen su archivo. Las preferencias (idioma, paleta, esquema de nombres y separador CSV) se guardan solo en este navegador, nunca el contenido del archivo.",
    guide_title    = "📋 Cómo nombrar las muestras en WinRhizo",
    guide_intro    = "Para evitar ambigüedades en el momento del análisis, conviene definir una convención de nombres antes de iniciar el escaneo. La app reconoce automáticamente dos esquemas:",
    guide_case1_title = "Caso simple — una sola réplica por muestra",
    guide_case1_body  = "Usa el formato TRATAMIENTO_réplica, con un guión bajo antes del número secuencial.",
    guide_case1_ex1   = "TRATAMIENTO_1, TRATAMIENTO_2, TRATAMIENTO_3 …",
    guide_case2_title = "Caso con dos niveles — réplica biológica y técnica",
    guide_case2_body  = "Si cada maceta contiene varias plantas (o varios submuestras), conviene distinguir entre la réplica biológica (la maceta, es decir, un individuo o grupo independiente) y la réplica técnica (la planta individual o medida repetida dentro de la misma maceta). Usa TRATAMIENTO.maceta.planta, con un punto antes de los dos números:",
    guide_case2_ex1   = "TRATAMIENTO.1.1, TRATAMIENTO.1.2 → maceta 1, plantas 1 y 2",
    guide_case2_ex2   = "TRATAMIENTO.2.1, TRATAMIENTO.2.2 → maceta 2, plantas 1 y 2",
    guide_why_title   = "¿Por qué un punto y no un guión bajo para maceta/planta?",
    guide_why_body    = "Cuando el nombre del tratamiento está formado por varias palabras unidas con guiones bajos (p.ej. 100_PPM_UREA), la app no puede saber a simple vista dónde termina el nombre y dónde empiezan los números de maceta y planta: todos los guiones bajos son iguales. Usando el punto solo para introducir los números de réplica, el límite entre nombre y números siempre es reconocible.",
    guide_why_ex1     = "100_PPM_UREA_1_2 → ambiguo: el último '_1' podría ser parte del nombre o la maceta",
    guide_why_ex2     = "100_PPM_UREA.1.2 → claro: tratamiento 100_PPM_UREA, maceta 1, planta 2",
    guide_collapse    = "Contraer guía",
    guide_expand      = "Mostrar guía",
    status_waiting   = "Esperando",
    status_loaded    = "✓ Archivo cargado",
    status_clean     = "✓ Archivo limpio",
    status_trt       = "✓ Tratamientos añadidos",
    status_final     = "✓ Archivo final listo",
    status_error     = "✗ Error",
    step1            = "1 — Cargar archivo",
    file_placeholder = "Selecciona uno o más archivos .txt exportados de WinRhizo…",
    file_btn         = "Examinar",
    example_btn      = "Probar con datos de ejemplo",
    example_note     = "Datos de ejemplo sintéticos, no mediciones reales.",
    file_info        = function(nr, nc) paste0(nr, " muestras · ", nc, " columnas detectadas"),
    files_merged     = function(n) paste0(n, " archivos unidos"),
    files_cols_warning = "Los archivos no tienen todos las mismas columnas. Quedan vacías para las muestras de los archivos que no las tienen:",
    step2            = "2 — Seleccionar columnas a conservar",
    sel_all          = "Seleccionar todo",
    desel_all        = "Deseleccionar todo",
    derived_note     = "Las columnas con borde discontinuo las calcula la app: TipsPerLength = Tips / Length(cm), ForksPerLength = Forks / Length(cm).",
    col_meta         = "columnas seleccionadas",
    col_of           = "de",
    err_no_cols      = "Selecciona al menos una columna antes de generar el archivo limpio.",
    step3            = "3 — Generar archivo limpio",
    btn_clean        = "Limpiar",
    btn_dl_clean     = "Descargar CSV limpio",
    csv_sep_lbl      = "Separador de los archivos CSV:",
    csv_sep_semicolon = "; punto y coma",
    csv_sep_comma    = ", coma",
    csv_sep_hint     = "Se aplica a todos los CSV descargados. Excel en español usa ';', Excel en inglés ','.",
    summary          = "Resumen",
    renamed_lbl      = "Columnas renombradas automáticamente:",
    stat_samples     = "muestras",
    stat_cols        = "columnas",
    stat_file        = "nombre archivo",
    preview8         = "Vista previa de datos",
    step4            = "4 — Asignar tratamientos a las muestras",
    trt_hint         = "WinRhizo codifica el tratamiento en el nombre de la muestra. Elige el esquema que corresponda a tu diseño experimental y revisa o modifica el tratamiento personalizado para cada muestra.",
    trt_scheme_lbl   = "Esquema del nombre de muestra:",
    trt_scheme_1     = "Tratamiento_Réplica",
    trt_scheme_1_sub = "p.ej. XYZ_3 → tratamiento XYZ, réplica 3",
    trt_scheme_2     = "Tratamiento.Maceta.Planta",
    trt_scheme_2_sub = "p.ej. X_Y_Z.1.2 → tratamiento X_Y_Z, maceta 1, planta 2",
    trt_scheme_3     = "Manual",
    trt_scheme_3_sub = "asigna tú mismo el rol de cada parte del nombre",
    trt_manual_lbl   = "Asigna un rol a cada parte del SampleId:",
    trt_manual_hint  = "Basado en la primera muestra del archivo. Reconoce guión bajo, punto y espacio como separadores. Los segmentos consecutivos con el mismo rol 'Tratamiento' se fusionan automáticamente.",
    trt_manual_role_treatment = "Tratamiento",
    trt_manual_role_pot       = "Maceta",
    trt_manual_role_plant     = "Planta",
    trt_manual_role_ignore    = "Ignorar",
    trt_manual_mismatch = "Aviso: algunos SampleIds tienen una estructura diferente a la muestra de referencia y no se han interpretado correctamente (se muestra el nombre original como tratamiento).",
    trt_scheme_mismatch = "Aviso: algunos SampleIds no siguen el esquema elegido. Se usa el nombre original como tratamiento y las réplicas quedan vacías.",
    trt_col_sample   = "SampleId",
    trt_col_detected = "Tratamiento detectado",
    trt_col_replica  = "Réplica",
    trt_col_vaso     = "Maceta (rep. biológica)",
    trt_col_pianta   = "Planta (rep. técnica)",
    trt_col_custom   = "Tratamiento personalizado",
    btn_trt          = "Añadir columnas de tratamiento y réplica",
    trt_preview      = "Vista previa con tratamientos",
    btn_dl_trt       = "Descargar CSV con tratamientos",
    step_qc          = "5 — Control de calidad",
    qc_hint          = "Controles automáticos: escaneos duplicados, valores faltantes o cero, posibles valores atípicos por tratamiento (a más de 5 MAD de la mediana en escala logarítmica, para longitud, superficie, diámetro y volumen, con al menos 5 muestras) y réplicas desequilibradas. Las muestras excluidas no entran en el archivo final, la tabla ni el gráfico.",
    qc_stat_flagged  = "por revisar",
    qc_stat_excluded = "excluidas",
    qc_none          = "Sin avisos: no se detectan problemas evidentes.",
    qc_balance_lbl   = "Réplicas desequilibradas",
    qc_units_pot     = "macetas por tratamiento",
    qc_units         = "réplicas por tratamiento",
    qc_single        = "Con una sola réplica no se pueden calcular SD y SE.",
    qc_drop_dups     = "Excluir los escaneos duplicados más antiguos",
    qc_dups_by_time  = "De cada duplicado se conserva el escaneo más reciente, según la fecha y la hora.",
    qc_dups_by_order = "Fecha y hora no legibles: de cada duplicado se conserva el último escaneo del archivo.",
    qc_show_all_label = "Mostrar todas las muestras",
    qc_show_all_sub  = "Para excluir también muestras sin avisos",
    qc_col_include   = "Incluir",
    qc_col_issues    = "Avisos",
    qc_issue_duplicate = "Duplicado",
    qc_issue_missing = "Faltante",
    qc_issue_zero    = "Cero",
    qc_issue_outlier = "Posible valor atípico",
    qc_reset         = "Volver a incluir todas las muestras",
    qc_regen_note    = "Después de cada cambio, vuelve a generar el archivo final en el paso 6.",
    btn_dl_qc        = "Descargar informe QC (CSV)",
    qc_all_excluded  = "Todas las muestras están excluidas: incluye al menos una en el paso 5.",
    step_final       = "6 — Formato final y descarga",
    pivot_label      = "Transponer parámetros a formato largo",
    pivot_sub        = "Las columnas numéricas se unirán en una columna 'parameter' con los valores en 'value'",
    btn_final        = "Generar archivo final",
    btn_dl_final     = "Descargar CSV final",
    stat_rows        = "filas",
    stat_format      = "formato",
    stat_excluded    = "excluidas (QC)",
    final_preview    = "Vista previa del archivo final",
    step_summary     = "7 — Tabla resumen",
    summary_hint     = "Media, desviación estándar (SD), error estándar (SE) y n por tratamiento, para todos los parámetros numéricos. Los tratamientos siguen el orden elegido en el paso 8.",
    summary_pot_note = "Esquema Maceta/Planta: las plantas de la misma maceta (réplicas técnicas) se promedian primero por maceta. Media, SD, SE y n se calculan entre macetas (réplicas biológicas).",
    btn_dl_summary   = "Descargar tabla CSV",
    step_chart       = "8 — Gráfico exploratorio",
    chart_param_lbl  = "Seleccionar parámetros a visualizar:",
    chart_hint       = "Solo para control de calidad rápido — no sustituye al análisis estadístico.",
    chart_pot_note   = "Esquema Maceta/Planta: las plantas de la misma maceta (réplicas técnicas) se promedian primero por maceta. Media, SE, cajas, puntos y n se calculan entre macetas (réplicas biológicas).",
    chart_type_lbl   = "Tipo de gráfico:",
    chart_type_bar   = "Barras",
    chart_type_bar_sub = "media ± SE",
    chart_type_box   = "Boxplot",
    chart_type_box_sub = "mediana, cuartiles, bigotes",
    chart_type_points = "Puntos",
    chart_type_points_sub = "cada réplica, media ± SE",
    palette_lbl      = "Paleta de colores:",
    palette_npg_sub  = "colores vivos, predeterminada",
    palette_okabe_sub = "apta para daltonismo",
    palette_gray     = "Escala de grises",
    palette_gray_sub = "para impresión en blanco y negro",
    order_lbl        = "Orden de los tratamientos:",
    order_hint       = "El primer tratamiento es la referencia de la vista % del control.",
    order_left       = "Mover a la izquierda",
    order_right      = "Mover a la derecha",
    pct_label        = "Mostrar como % del control",
    pct_sub          = "Cada valor se divide por la media del primer tratamiento de la lista (= 100%)",
    btn_chart        = "Generar gráfico",
    btn_dl_png       = "Descargar PNG",
    btn_dl_pdf       = "Descargar PDF",
    btn_dl_svg       = "Descargar SVG",
    err_export       = "Este formato no está disponible en este navegador.",
    btn_clear        = "Borrar gráfico",
    chart_no_params  = "No hay parámetros numéricos disponibles en el archivo final.",
    chart_ylab       = "Valor medio",
    chart_ylab_value = "Valor",
    chart_ylab_pct   = "% del control",
    chart_no_ref     = "Media de referencia no disponible",
    jitter_label     = "Mostrar puntos individuales (jitter)",
    jitter_sub       = "Superponer cada medición como un punto, útil para detectar valores atípicos",
    credits          = list(
      pre  = "Aplicación desarrollada por ",
      bug  = " · Reportar problemas en ",
      or   = " o por ",
      mail = "correo"
    )
  ),
  fr = list(
    app_subtitle     = "Nettoyage des données de morphologie racinaire depuis",
    app_descr        = "Logiciel d'analyse de l'architecture racinaire à partir d'images numérisées — Regent Instruments.",
    privacy_title    = "Votre fichier reste dans le navigateur",
    privacy_body     = "Cette application s'exécute entièrement dans votre navigateur grâce à WebR : le fichier que vous chargez est traité uniquement sur votre appareil et n'est jamais envoyé à un serveur. Une connexion n'est nécessaire que pour ouvrir la page ; ensuite, l'application fonctionne aussi hors ligne. Au premier démarrage, quelques secondes peuvent être nécessaires pour initialiser l'environnement R. Comme toute page web, elle est fournie par un service d'hébergement, qui reçoit des données techniques telles que l'adresse IP. Google Analytics n'est chargé qu'avec votre consentement, pour collecter des statistiques d'utilisation qui n'incluent jamais votre fichier. Les préférences (langue, palette, schéma des noms et séparateur CSV) sont enregistrées uniquement dans ce navigateur, jamais le contenu du fichier.",
    guide_title    = "📋 Comment nommer les échantillons dans WinRhizo",
    guide_intro    = "Pour éviter toute ambiguïté lors de l'analyse, il est utile de définir une convention de nommage avant de commencer le balayage. L'application reconnaît automatiquement deux schémas :",
    guide_case1_title = "Cas simple — une seule réplique par échantillon",
    guide_case1_body  = "Utilisez le format TRAITEMENT_réplique, avec un underscore avant le numéro séquentiel.",
    guide_case1_ex1   = "TRAITEMENT_1, TRAITEMENT_2, TRAITEMENT_3 …",
    guide_case2_title = "Cas à deux niveaux — réplique biologique et technique",
    guide_case2_body  = "Si chaque pot contient plusieurs plantes (ou plusieurs sous-échantillons), il convient de distinguer la réplique biologique (le pot, c'est-à-dire un individu ou groupe indépendant) de la réplique technique (la plante individuelle ou mesure répétée dans le même pot). Utilisez TRAITEMENT.pot.plante, avec un point avant les deux chiffres :",
    guide_case2_ex1   = "TRAITEMENT.1.1, TRAITEMENT.1.2 → pot 1, plantes 1 et 2",
    guide_case2_ex2   = "TRAITEMENT.2.1, TRAITEMENT.2.2 → pot 2, plantes 1 et 2",
    guide_why_title   = "Pourquoi un point plutôt qu'un underscore pour pot/plante ?",
    guide_why_body    = "Lorsque le nom du traitement est composé de plusieurs mots reliés par des underscores (ex. 100_PPM_UREA), l'application ne peut pas savoir d'emblée où le nom se termine et où commencent les numéros de pot et de plante : tous les underscores se ressemblent. En utilisant le point uniquement pour introduire les numéros de réplique, la frontière entre nom et chiffres reste reconnaissable.",
    guide_why_ex1     = "100_PPM_UREA_1_2 → ambigu : le dernier '_1' pourrait faire partie du nom ou être le pot",
    guide_why_ex2     = "100_PPM_UREA.1.2 → clair : traitement 100_PPM_UREA, pot 1, plante 2",
    guide_collapse    = "Réduire le guide",
    guide_expand      = "Afficher le guide",
    status_waiting   = "En attente",
    status_loaded    = "✓ Fichier chargé",
    status_clean     = "✓ Fichier nettoyé",
    status_trt       = "✓ Traitements ajoutés",
    status_final     = "✓ Fichier final prêt",
    status_error     = "✗ Erreur",
    step1            = "1 — Charger le fichier",
    file_placeholder = "Sélectionnez un ou plusieurs fichiers .txt exportés de WinRhizo…",
    file_btn         = "Parcourir",
    example_btn      = "Essayer avec des données d'exemple",
    example_note     = "Données d'exemple synthétiques, pas de vraies mesures.",
    file_info        = function(nr, nc) paste0(nr, " échantillons · ", nc, " colonnes détectées"),
    files_merged     = function(n) paste0(n, " fichiers fusionnés"),
    files_cols_warning = "Les fichiers n'ont pas tous les mêmes colonnes. Elles restent vides pour les échantillons des fichiers qui ne les contiennent pas :",
    step2            = "2 — Sélectionner les colonnes à conserver",
    sel_all          = "Tout sélectionner",
    desel_all        = "Tout désélectionner",
    derived_note     = "Les colonnes en pointillés sont calculées par l'application : TipsPerLength = Tips / Length(cm), ForksPerLength = Forks / Length(cm).",
    col_meta         = "colonnes sélectionnées",
    col_of           = "sur",
    err_no_cols      = "Sélectionnez au moins une colonne avant de générer le fichier nettoyé.",
    step3            = "3 — Générer le fichier nettoyé",
    btn_clean        = "Nettoyer",
    btn_dl_clean     = "Télécharger le CSV nettoyé",
    csv_sep_lbl      = "Séparateur des fichiers CSV :",
    csv_sep_semicolon = "; point-virgule",
    csv_sep_comma    = ", virgule",
    csv_sep_hint     = "S'applique à tous les CSV téléchargés. Excel en français utilise ';', Excel en anglais ','.",
    summary          = "Récapitulatif",
    renamed_lbl      = "Colonnes renommées automatiquement :",
    stat_samples     = "échantillons",
    stat_cols        = "colonnes",
    stat_file        = "nom du fichier",
    preview8         = "Aperçu des données",
    step4            = "4 — Assigner les traitements aux échantillons",
    trt_hint         = "WinRhizo encode le traitement dans le nom de l'échantillon. Choisissez le schéma correspondant à votre dispositif expérimental, puis vérifiez ou modifiez le traitement personnalisé pour chaque échantillon.",
    trt_scheme_lbl   = "Schéma du nom d'échantillon :",
    trt_scheme_1     = "Traitement_Réplique",
    trt_scheme_1_sub = "ex. XYZ_3 → traitement XYZ, réplique 3",
    trt_scheme_2     = "Traitement.Pot.Plante",
    trt_scheme_2_sub = "ex. X_Y_Z.1.2 → traitement X_Y_Z, pot 1, plante 2",
    trt_scheme_3     = "Manuel",
    trt_scheme_3_sub = "assignez vous-même le rôle de chaque partie du nom",
    trt_manual_lbl   = "Assignez un rôle à chaque partie du SampleId :",
    trt_manual_hint  = "Basé sur le premier échantillon du fichier. Reconnaît l'underscore, le point et l'espace comme séparateurs. Les segments consécutifs avec le même rôle 'Traitement' sont fusionnés automatiquement.",
    trt_manual_role_treatment = "Traitement",
    trt_manual_role_pot       = "Pot",
    trt_manual_role_plant     = "Plante",
    trt_manual_role_ignore    = "Ignorer",
    trt_manual_mismatch = "Avertissement : certains SampleIds ont une structure différente de l'échantillon de référence et n'ont pas été interprétés correctement (le nom original est affiché comme traitement).",
    trt_scheme_mismatch = "Avertissement : certains SampleIds ne respectent pas le schéma choisi. Le nom original est utilisé comme traitement et les répliques restent vides.",
    trt_col_sample   = "SampleId",
    trt_col_detected = "Traitement détecté",
    trt_col_replica  = "Réplique",
    trt_col_vaso     = "Pot (rép. biologique)",
    trt_col_pianta   = "Plante (rép. technique)",
    trt_col_custom   = "Traitement personnalisé",
    btn_trt          = "Ajouter les colonnes traitement et réplique",
    trt_preview      = "Aperçu avec traitements",
    btn_dl_trt       = "Télécharger le CSV avec traitements",
    step_qc          = "5 — Contrôle qualité",
    qc_hint          = "Contrôles automatiques : scans en double, valeurs manquantes ou nulles, valeurs aberrantes possibles par traitement (à plus de 5 MAD de la médiane en échelle logarithmique, pour la longueur, la surface, le diamètre et le volume, avec au moins 5 échantillons) et répétitions déséquilibrées. Les échantillons exclus ne figurent ni dans le fichier final, ni dans le tableau, ni dans le graphique.",
    qc_stat_flagged  = "à vérifier",
    qc_stat_excluded = "exclus",
    qc_none          = "Aucun signalement : pas de problème évident.",
    qc_balance_lbl   = "Répétitions déséquilibrées",
    qc_units_pot     = "pots par traitement",
    qc_units         = "répétitions par traitement",
    qc_single        = "Avec une seule répétition, SD et SE ne peuvent pas être calculés.",
    qc_drop_dups     = "Exclure les scans en double les plus anciens",
    qc_dups_by_time  = "Pour chaque doublon, le scan le plus récent est conservé, d'après la date et l'heure.",
    qc_dups_by_order = "Date et heure illisibles : pour chaque doublon, le dernier scan du fichier est conservé.",
    qc_show_all_label = "Afficher tous les échantillons",
    qc_show_all_sub  = "Pour exclure aussi des échantillons sans signalement",
    qc_col_include   = "Inclure",
    qc_col_issues    = "Signalements",
    qc_issue_duplicate = "Doublon",
    qc_issue_missing = "Manquant",
    qc_issue_zero    = "Zéro",
    qc_issue_outlier = "Valeur aberrante possible",
    qc_reset         = "Réinclure tous les échantillons",
    qc_regen_note    = "Après chaque modification, régénérez le fichier final à l'étape 6.",
    btn_dl_qc        = "Télécharger le rapport QC (CSV)",
    qc_all_excluded  = "Tous les échantillons sont exclus : incluez-en au moins un à l'étape 5.",
    step_final       = "6 — Format final et téléchargement",
    pivot_label      = "Transposer les paramètres en format long",
    pivot_sub        = "Les colonnes numériques seront fusionnées dans une colonne 'parameter' avec les valeurs dans 'value'",
    btn_final        = "Générer le fichier final",
    btn_dl_final     = "Télécharger le CSV final",
    stat_rows        = "lignes",
    stat_format      = "format",
    stat_excluded    = "exclus (QC)",
    final_preview    = "Aperçu du fichier final",
    step_summary     = "7 — Tableau récapitulatif",
    summary_hint     = "Moyenne, écart type (SD), erreur standard (SE) et n par traitement, pour tous les paramètres numériques. Les traitements suivent l'ordre choisi à l'étape 8.",
    summary_pot_note = "Schéma Pot/Plante : les plantes d'un même pot (répétitions techniques) sont d'abord moyennées par pot. Moyenne, SD, SE et n sont calculés entre pots (répétitions biologiques).",
    btn_dl_summary   = "Télécharger le tableau CSV",
    step_chart       = "8 — Graphique exploratoire",
    chart_param_lbl  = "Sélectionner les paramètres à afficher :",
    chart_hint       = "À des fins de contrôle qualité uniquement — ne remplace pas une analyse statistique.",
    chart_pot_note   = "Schéma Pot/Plante : les plantes d'un même pot (répétitions techniques) sont d'abord moyennées par pot. Moyenne, SE, boîtes, points et n sont calculés entre pots (répétitions biologiques).",
    chart_type_lbl   = "Type de graphique :",
    chart_type_bar   = "Barres",
    chart_type_bar_sub = "moyenne ± SE",
    chart_type_box   = "Boxplot",
    chart_type_box_sub = "médiane, quartiles, moustaches",
    chart_type_points = "Points",
    chart_type_points_sub = "chaque réplique, moyenne ± SE",
    palette_lbl      = "Palette de couleurs :",
    palette_npg_sub  = "couleurs vives, par défaut",
    palette_okabe_sub = "adaptée au daltonisme",
    palette_gray     = "Niveaux de gris",
    palette_gray_sub = "pour l'impression en noir et blanc",
    order_lbl        = "Ordre des traitements :",
    order_hint       = "Le premier traitement est la référence de la vue % du témoin.",
    order_left       = "Déplacer à gauche",
    order_right      = "Déplacer à droite",
    pct_label        = "Afficher en % du témoin",
    pct_sub          = "Chaque valeur est divisée par la moyenne du premier traitement de la liste (= 100%)",
    btn_chart        = "Générer le graphique",
    btn_dl_png       = "Télécharger PNG",
    btn_dl_pdf       = "Télécharger PDF",
    btn_dl_svg       = "Télécharger SVG",
    err_export       = "Ce format n'est pas disponible dans ce navigateur.",
    btn_clear        = "Effacer le graphique",
    chart_no_params  = "Aucun paramètre numérique disponible dans le fichier final.",
    chart_ylab       = "Valeur moyenne",
    chart_ylab_value = "Valeur",
    chart_ylab_pct   = "% du témoin",
    chart_no_ref     = "Moyenne de référence non disponible",
    jitter_label     = "Afficher les points individuels (jitter)",
    jitter_sub       = "Superposer chaque mesure sous forme de point, utile pour repérer les valeurs aberrantes",
    credits          = list(
      pre  = "Application développée par ",
      bug  = " · Signaler des problèmes sur ",
      or   = " ou via ",
      mail = "e-mail"
    )
  )
)

# ── Parsing WinRhizo ──────────────────────────────────────────────────────────
# Il file WinRhizo ha l'header delle colonne dati in riga 1 (prima colonna
# "RHIZO <versione>", es. "RHIZO 2021a"), seguito da alcune righe di sub-header
# per altri tipi di record (COLOR, LINK, DEV, AXIS) che vanno scartate.
# v1.1: la prima colonna diventa sempre "SampleId", qualunque sia la versione
# di WinRhizo, e le righe dati sono riconosciute dal contenuto (almeno un valore
# numerico nelle colonne morfologiche) invece che dalla posizione fissa (riga 6).

# Colonne WinRhizo sempre numeriche, usate per riconoscere le righe di dati
WR_NUMERIC_HINT <- c("Length(cm)", "ProjArea(cm2)", "SurfArea(cm2)",
                     "AvgDiam(mm)", "RootVolume(cm3)", "Tips", "Forks", "Crossings")

# TRUE se la stringa è un numero (punto o virgola come separatore decimale)
is_num_like <- function(x) {
  grepl("^\\s*[-+]?[0-9]+([.,][0-9]+)?([eE][-+]?[0-9]+)?\\s*$", x) |
  grepl("^\\s*[-+]?[.,][0-9]+\\s*$", x)
}

# Converte la virgola decimale in punto nelle colonne interamente numeriche
# (export WinRhizo con impostazioni locali italiane/europee: "12,345").
fix_decimal_comma <- function(df, skip = "SampleId") {
  for (cn in setdiff(colnames(df), skip)) {
    v  <- df[[cn]]
    nz <- !is.na(v) & trimws(v) != ""
    if (any(nz) && all(is_num_like(v[nz])) && any(grepl(",", v[nz], fixed = TRUE))) {
      df[[cn]] <- sub(",", ".", v, fixed = TRUE)
    }
  }
  df
}

# Legge il file come testo UTF-8. Gli export da Windows possono essere in
# Windows-1252/Latin-1 (es. "Prè_1"): in questo caso vengono convertiti.
read_lines_utf8 <- function(filepath) {
  lines <- readLines(filepath, warn = FALSE)
  if (all(validUTF8(lines))) {
    Encoding(lines) <- "UTF-8"
    return(lines)
  }
  converted <- iconv(lines, from = "CP1252", to = "UTF-8")
  if (anyNA(converted)) converted <- iconv(lines, from = "latin1", to = "UTF-8")
  converted
}

parse_winrhizo <- function(filepath) {
  lines <- read_lines_utf8(filepath)
  lines <- gsub("\r", "", lines)
  lines <- sub("^", "", lines)                # BOM eventuale
  header <- trimws(strsplit(lines[1], "\t")[[1]])
  orig_id_col <- header[1]
  header[1]   <- "SampleId"                         # qualsiasi "RHIZO <versione>"
  n_cols      <- length(header)

  body <- lines[-1]
  body <- body[nchar(trimws(body)) > 0]
  split_rows <- lapply(strsplit(body, "\t"), function(x) {
    length(x) <- n_cols; x[is.na(x)] <- ""; trimws(x)
  })

  hint_idx <- which(header %in% WR_NUMERIC_HINT)
  if (length(hint_idx)) {
    is_data <- vapply(split_rows, function(x) {
      nzchar(x[1]) && any(is_num_like(x[hint_idx]))
    }, logical(1))
  } else {
    # colonne non riconosciute: comportamento storico (dati dalla riga 6)
    is_data <- seq_along(split_rows) >= 5
  }
  split_rows <- split_rows[is_data]
  if (!length(split_rows)) stop("No data rows found in the WinRhizo file.")

  df           <- as.data.frame(do.call(rbind, split_rows), stringsAsFactors = FALSE)
  colnames(df) <- header
  df <- df[, colnames(df) != "", drop = FALSE]
  df <- fix_decimal_comma(df)
  attr(df, "orig_id_col") <- orig_id_col
  df
}

# ── Tratti derivati, calcolati dalle colonne di WinRhizo ─────────────────────
# Vuoti quando la lunghezza è zero o mancante. Non selezionati di default.
DERIVED_TRAITS <- list(
  "TipsPerLength(1/cm)"  = c(num = "Tips",  den = "Length(cm)"),
  "ForksPerLength(1/cm)" = c(num = "Forks", den = "Length(cm)")
)

add_derived_traits <- function(df) {
  for (nm in names(DERIVED_TRAITS)) {
    d <- DERIVED_TRAITS[[nm]]
    if (!all(d %in% colnames(df)) || nm %in% colnames(df)) next
    val <- suppressWarnings(as.numeric(df[[d[["num"]]]]) / as.numeric(df[[d[["den"]]]]))
    df[[nm]] <- ifelse(is.finite(val), sprintf("%.4f", val), "")
  }
  df
}

# ── Più file: unione per nome di colonna ─────────────────────────────────────
# Le colonne che mancano in un file restano vuote per i suoi campioni;
# source_file dice da quale file viene ogni campione (solo con più file).
read_winrhizo_files <- function(paths, names = basename(paths)) {
  dfs <- lapply(seq_along(paths), function(i) {
    tryCatch(parse_winrhizo(paths[i]),
             error = function(e) stop(names[i], ": ", conditionMessage(e), call. = FALSE))
  })
  orig_ids <- unique(vapply(dfs, function(d) attr(d, "orig_id_col"), ""))
  missing  <- character()
  if (length(dfs) == 1) {
    out <- dfs[[1]]
  } else {
    all_cols <- unique(unlist(lapply(dfs, colnames)))
    missing  <- unique(unlist(lapply(dfs, function(d) setdiff(all_cols, colnames(d)))))
    out <- do.call(rbind, lapply(seq_along(dfs), function(i) {
      d <- dfs[[i]]
      for (cn in setdiff(all_cols, colnames(d))) d[[cn]] <- ""
      d <- d[, all_cols, drop = FALSE]
      d$source_file <- names[i]
      d
    }))
    rownames(out) <- NULL
  }
  out <- add_derived_traits(out)
  attr(out, "orig_id_col")  <- paste(orig_ids, collapse = ", ")
  attr(out, "n_files")      <- length(dfs)
  attr(out, "missing_cols") <- if (is.null(missing)) character() else missing
  out
}

# ── Estrazione trattamento/repliche dal SampleId, con livelli configurabili ──
# n_levels = 1: TRATTAMENTO_replica            (es. "XYZ_3" o "XYZ.3")
# n_levels = 2: TRATTAMENTO_vaso(.|_)pianta    (es. "X_Y_Z_1_2", "X_Y_Z_1.2" o "X_Y_Z.1.2")
# Il separatore puo' essere "_" oppure "." sia tra trattamento e primo numero
# sia tra i numeri successivi (entrambi accettati, anche mescolati nello
# stesso file). Convenzione consigliata: "_" per unire le parole del nome
# trattamento, "." per separare i livelli di replica, es. "X_Y_Z.1.2".
extract_treatment <- function(sample_ids, n_levels = 1) {
  pattern <- paste0("[_.]\\d+([_.]\\d+){", n_levels - 1, "}$")
  gsub(pattern, "", sample_ids)
}

# Estrae gli ultimi n_levels numeri come lista di vettori (uno per livello,
# in ordine: livello 1 = più esterno/biologico, livello n = più interno/tecnico)
extract_replicate_levels <- function(sample_ids, n_levels = 1) {
  pattern <- paste0("[_.](\\d+)([_.](\\d+)){", n_levels - 1, "}$")
  rx  <- regexpr(pattern, sample_ids)
  m   <- regmatches(sample_ids, rx)   # solo i campioni che rispettano lo schema
  out <- lapply(seq_len(n_levels), function(lvl) rep(NA_character_, length(sample_ids)))

  has_match <- as.vector(rx) > 0
  if (any(has_match)) {
    cleaned <- sub("^[_.]", "", m)
    nums    <- strsplit(cleaned, "[_.]")
    for (lvl in seq_len(n_levels)) {
      vals <- vapply(nums, function(x) if (length(x) >= lvl) x[lvl] else NA_character_, character(1))
      out[[lvl]][has_match] <- vals
    }
  }
  out
}

# ── Schema manuale: scompone un SampleId in token + separatori ──────────────
split_sampleid_tokens <- function(sample_id) {
  # Separatori consecutivi contano come uno solo; quelli iniziali e finali
  # vengono ignorati: "A__1.2" e "_A_1.2." hanno le stesse parti di "A_1.2".
  tokens <- regmatches(sample_id, gregexpr("[^_. ]+", sample_id, perl = TRUE))[[1]]
  seps   <- regmatches(sample_id, gregexpr("[_. ]+", sample_id, perl = TRUE))[[1]]
  if (grepl("^[_. ]", sample_id)) seps <- seps[-1]
  if (grepl("[_. ]$", sample_id) && length(seps)) seps <- seps[-length(seps)]
  list(tokens = tokens, seps = substr(seps, 1, 1))
}

# Applica una mappatura di ruoli (uno per token, posizionale) a tutti i
# sample_id, assumendo la stessa struttura del campione di riferimento usato
# per generare i dropdown. Ruoli ammessi: "Treatment", "Pot", "Plant", "Ignore".
# Segmenti "Treatment" consecutivi vengono uniti col separatore originale.
apply_manual_scheme <- function(sample_ids, roles) {
  n <- length(sample_ids)
  treatment <- character(n)
  pot       <- rep(NA_character_, n)
  plant     <- rep(NA_character_, n)
  ok        <- rep(TRUE, n)

  for (i in seq_len(n)) {
    sp <- split_sampleid_tokens(sample_ids[i])
    if (length(sp$tokens) != length(roles)) {
      ok[i] <- FALSE
      treatment[i] <- sample_ids[i]
      next
    }
    trt_parts <- character(0)
    for (j in seq_along(roles)) {
      if (roles[j] == "Treatment") {
        if (length(trt_parts) > 0) trt_parts <- c(trt_parts, sp$seps[j - 1])
        trt_parts <- c(trt_parts, sp$tokens[j])
      } else if (roles[j] == "Pot") {
        pot[i] <- sp$tokens[j]
      } else if (roles[j] == "Plant") {
        plant[i] <- sp$tokens[j]
      }
    }
    treatment[i] <- paste(trt_parts, collapse = "")
  }

  list(treatment = treatment, pot = pot, plant = plant, ok = ok)
}

apply_rename <- function(df) {
  for (old in names(COL_RENAME)) {
    idx <- which(colnames(df) == old)
    if (length(idx)) colnames(df)[idx[1]] <- COL_RENAME[[old]]
  }
  df
}

pivot_long <- function(df) {
  id_cols    <- c("SampleId", "datetime", "treatment", "replicate", "pot", "plant", "source_file")
  id_present <- id_cols[id_cols %in% colnames(df)]
  param_cols <- setdiff(colnames(df), id_present)
  if (!length(param_cols)) return(df)
  id_data   <- df[, id_present, drop = FALSE]
  long_rows <- do.call(rbind, lapply(param_cols, function(p) {
    tmp <- id_data; tmp$parameter <- p; tmp$value <- df[[p]]; tmp
  }))
  long_rows <- long_rows[order(rep(seq_len(nrow(df)), length(param_cols))), ]
  rownames(long_rows) <- NULL
  long_rows
}

# ── Calcolo media + SE per trattamento ────────────────────────────────────────
compute_mean_se <- function(df, param, trt_col = "treatment") {
  vals <- suppressWarnings(as.numeric(df[[param]]))
  trt  <- df[[trt_col]]
  ok   <- !is.na(vals) & !is.na(trt)
  vals <- vals[ok]; trt <- trt[ok]
  if (!length(vals)) return(NULL)

  agg_mean <- tapply(vals, trt, mean, na.rm = TRUE)
  agg_se   <- tapply(vals, trt, function(x) {
    n <- sum(!is.na(x))
    if (n < 2) return(0)
    sd(x, na.rm = TRUE) / sqrt(n)
  })
  agg_n    <- tapply(vals, trt, function(x) sum(!is.na(x)))
  data.frame(
    treatment = names(agg_mean),
    mean      = as.numeric(agg_mean),
    se        = as.numeric(agg_se[names(agg_mean)]),
    n         = as.integer(agg_n[names(agg_mean)]),
    stringsAsFactors = FALSE
  )
}

# ── Unità sperimentale per il grafico (v1.1) ─────────────────────────────────
# Con lo schema Vaso/Pianta le piante dello stesso vaso sono repliche tecniche:
# vengono prima mediate per vaso, così media e SE sono calcolati tra vasi
# (repliche biologiche) e n = numero di vasi. Senza colonna "pot" ogni riga è
# già un'unità indipendente. I campioni senza vaso riconosciuto restano unità
# singole.
has_pot_level <- function(df) {
  "pot" %in% colnames(df) && any(!is.na(df$pot) & df$pot != "")
}

collapse_to_unit <- function(df, param, trt_col = "treatment") {
  vals <- suppressWarnings(as.numeric(df[[param]]))
  trt  <- as.character(df[[trt_col]])
  if (!has_pot_level(df)) {
    out <- data.frame(trt = trt, v = vals, stringsAsFactors = FALSE)
  } else {
    pot  <- as.character(df$pot)
    key  <- ifelse(is.na(pot) | pot == "", paste0(".row", seq_along(pot)), pot)
    ok   <- !is.na(vals) & !is.na(trt)
    if (!any(ok)) return(NULL)
    out <- aggregate(vals[ok], by = list(trt = trt[ok], unit = key[ok]), FUN = mean)
    out <- data.frame(trt = out$trt, v = out$x, stringsAsFactors = FALSE)
  }
  names(out) <- c(trt_col, param)
  out
}

# ── Controllo qualità ────────────────────────────────────────────────────────
# Segnala senza escludere nulla da solo: scansioni duplicate, valori mancanti,
# zeri nelle misure di dimensione e possibili outlier per trattamento.
QC_ISSUES        <- c("duplicate", "missing", "zero", "outlier")
QC_SIZE_COLS     <- c("Length(cm)", "ProjArea(cm2)", "SurfArea(cm2)", "AvgDiam(mm)", "RootVolume(cm3)")
# Outlier: |log(valore) - mediana| / MAD > 5, solo sulle misure principali e con
# almeno 5 campioni per trattamento. Con pochi campioni la soglia classica di 3,5
# segnala per errore circa un gruppo su sei (simulazione con dati log-normali,
# CV 25%, 6 campioni); con 5 si scende a circa il 6% e restano visibili le
# scansioni fallite o i detriti, che si discostano di molte volte dalla mediana.
QC_OUTLIER_COLS  <- c("Length(cm)", "SurfArea(cm2)", "AvgDiam(mm)", "RootVolume(cm3)")
QC_OUTLIER_MIN_N <- 5
QC_OUTLIER_Z     <- 5

# Formati di data e ora provati in ordine: giorno/mese prima di mese/giorno
# (strptime ignora i caratteri in più, quindi AM/PM ha formati a parte)
DATETIME_FORMATS <- c("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y/%m/%d %H:%M:%S", "%Y/%m/%d %H:%M",
                      "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M", "%d.%m.%Y %H:%M:%S", "%d.%m.%Y %H:%M",
                      "%m/%d/%Y %H:%M:%S", "%m/%d/%Y %H:%M")
DATETIME_FORMATS_AMPM <- c("%m/%d/%Y %I:%M:%S %p", "%m/%d/%Y %I:%M %p", "%Y-%m-%d %I:%M:%S %p")

# Il primo formato che legge tutti i valori; NULL se nessuno ci riesce
parse_scan_time <- function(x) {
  x  <- trimws(as.character(x))
  ok <- !is.na(x) & nzchar(x)
  if (!any(ok)) return(NULL)
  ampm <- any(grepl("[AaPp]\\.?[Mm]\\.?$", x[ok]))
  for (f in if (ampm) DATETIME_FORMATS_AMPM else DATETIME_FORMATS) {
    tm <- as.POSIXct(x, format = f, tz = "UTC")
    if (!anyNA(tm[ok])) return(tm)
  }
  NULL
}

sample_id_col <- function(df) if ("SampleId" %in% colnames(df)) "SampleId" else colnames(df)[1]

# Righe con lo stesso SampleId; "older" sono quelle da escludere per tenere la
# scansione più recente (per data e ora, altrimenti l'ultima nel file).
qc_duplicates <- function(df) {
  if (!"SampleId" %in% colnames(df)) return(list(rows = integer(), older = integer(), by_time = FALSE))
  ids <- as.character(df$SampleId)
  dup <- which(ids %in% ids[duplicated(ids)])
  tm  <- if ("datetime" %in% colnames(df)) parse_scan_time(df$datetime) else NULL
  if (!length(dup)) return(list(rows = integer(), older = integer(), by_time = !is.null(tm)))
  key <- if (is.null(tm)) seq_along(ids) else as.numeric(tm)
  older <- unlist(lapply(split(dup, ids[dup]), function(r) {
    setdiff(r, r[order(key[r], r, decreasing = TRUE)][1])
  }), use.names = FALSE)
  list(rows = dup, older = sort(as.integer(older)), by_time = !is.null(tm))
}

# Una riga per segnalazione: row, issue, parameter, value
qc_check <- function(df, params, trt_col = "treatment") {
  issues <- list()
  add <- function(row, issue, parameter = NA_character_, value = NA_character_) {
    issues[[length(issues) + 1]] <<- data.frame(row = as.integer(row), issue = issue, parameter = parameter,
                                                 value = as.character(value), stringsAsFactors = FALSE)
  }
  d <- qc_duplicates(df)
  if (length(d$rows)) {
    add(d$rows, "duplicate", value = if ("datetime" %in% colnames(df)) df$datetime[d$rows] else NA_character_)
  }
  for (p in params) {
    raw <- as.character(df[[p]])
    v   <- suppressWarnings(as.numeric(raw))
    miss <- which(is.na(v))
    if (length(miss)) add(miss, "missing", p, "")
    if (p %in% QC_SIZE_COLS) {
      zero <- which(!is.na(v) & v == 0)
      if (length(zero)) add(zero, "zero", p, raw[zero])
    }
  }
  if (trt_col %in% colnames(df)) {
    trt <- as.character(df[[trt_col]])
    for (p in intersect(params, QC_OUTLIER_COLS)) {
      v <- suppressWarnings(as.numeric(df[[p]]))
      for (g in unique(trt)) {
        idx <- which(trt == g & !is.na(v))
        if (length(idx) < QC_OUTLIER_MIN_N) next
        # scala logaritmica: le misure morfologiche sono positive e asimmetriche
        x <- if (all(v[idx] > 0)) log(v[idx]) else v[idx]
        s <- mad(x)
        if (!is.finite(s) || s == 0) next
        hit <- idx[abs(x - median(x)) / s > QC_OUTLIER_Z]
        if (length(hit)) add(hit, "outlier", p, df[[p]][hit])
      }
    }
  }
  if (!length(issues)) {
    return(data.frame(row = integer(), issue = character(), parameter = character(),
                      value = character(), stringsAsFactors = FALSE))
  }
  out <- do.call(rbind, issues)
  out <- out[order(out$row, match(out$issue, QC_ISSUES)), ]
  rownames(out) <- NULL
  out
}

# Unità sperimentali per trattamento (vasi, se presenti), come nel grafico
qc_balance <- function(df, trt_col = "treatment", trt_order = NULL) {
  if (!nrow(df) || !trt_col %in% colnames(df)) return(NULL)
  key <- if (has_pot_level(df)) {
    pot <- as.character(df$pot)
    ifelse(is.na(pot) | pot == "", paste0(".row", seq_along(pot)), pot)
  } else as.character(seq_len(nrow(df)))
  trts <- order_treatments(df[[trt_col]], trt_order)
  n <- vapply(trts, function(tr) length(unique(key[df[[trt_col]] == tr])), integer(1))
  data.frame(treatment = trts, n = unname(n), stringsAsFactors = FALSE)
}

# Report scaricabile: segnalazioni ed esclusioni manuali (issue = "manual")
qc_report <- function(df, issues, excluded) {
  manual <- setdiff(excluded, issues$row)
  rep <- rbind(issues, if (length(manual))
    data.frame(row = as.integer(manual), issue = "manual", parameter = NA_character_,
               value = NA_character_, stringsAsFactors = FALSE))
  rep <- rep[order(rep$row), , drop = FALSE]
  out <- data.frame(SampleId = df[[sample_id_col(df)]][rep$row], stringsAsFactors = FALSE)
  if ("treatment" %in% colnames(df))   out$treatment   <- df$treatment[rep$row]
  if ("source_file" %in% colnames(df)) out$source_file <- df$source_file[rep$row]
  out$issue     <- rep$issue
  out$parameter <- rep$parameter
  out$value     <- rep$value
  out$excluded  <- rep$row %in% excluded
  out
}

# ── Ordine dei trattamenti ───────────────────────────────────────────────────
# Predefinito: i nomi che sembrano un controllo per primi, poi ordine alfabetico.
# L'ordine scelto dall'utente ha la precedenza; i nomi che non esistono più
# vengono scartati e quelli nuovi vanno in coda.
CONTROL_PATTERN <- "(^|[_. -])(ctrl|ctr|control|controllo|controlli|contr\u00f4le|controle|t\u00e9moin|temoin|testigo|testimone|ck|mock|untreated)($|[_. -])"

order_treatments <- function(treatments, preferred = NULL) {
  u    <- sort(unique(as.character(treatments)))
  ctrl <- u[grepl(CONTROL_PATTERN, u, ignore.case = TRUE)]
  default <- c(ctrl, setdiff(u, ctrl))
  c(intersect(preferred, u), setdiff(default, preferred))
}

# ── Tabella riassuntiva ──────────────────────────────────────────────────────
# Stessa unità sperimentale del grafico (vasi, se presenti). Con n < 2, SD e SE
# non sono definiti e restano vuoti.
summary_table <- function(df, params, trt_col = "treatment", trt_order = NULL) {
  trts <- order_treatments(df[[trt_col]], trt_order)
  rows <- lapply(params, function(p) {
    unit_df <- collapse_to_unit(df, p, trt_col)
    do.call(rbind, lapply(trts, function(tr) {
      v <- if (is.null(unit_df)) numeric(0) else unit_df[[p]][which(unit_df[[trt_col]] == tr)]
      v <- v[!is.na(v)]
      n <- length(v)
      data.frame(parameter = p, treatment = tr, n = n,
                 mean = if (n > 0) mean(v) else NA_real_,
                 sd   = if (n > 1) sd(v) else NA_real_,
                 se   = if (n > 1) sd(v) / sqrt(n) else NA_real_,
                 stringsAsFactors = FALSE)
    }))
  })
  out <- do.call(rbind, rows)
  rownames(out) <- NULL
  out
}

# 5 cifre significative, senza notazione scientifica (100000, non 1e+05)
format_summary <- function(tbl) {
  fmt <- function(x) {
    out <- rep(NA_character_, length(x))
    out[!is.na(x)] <- vapply(x[!is.na(x)], format, "", digits = 5, scientific = FALSE, trim = TRUE)
    out
  }
  for (cn in c("mean", "sd", "se")) tbl[[cn]] <- fmt(tbl[[cn]])
  tbl
}

# ── Valori come % della media del trattamento di riferimento ─────────────────
# NULL se il riferimento non ha dati o ha media non positiva (divisione senza senso).
to_pct_of_control <- function(unit_df, param, ref, trt_col = "treatment") {
  v <- suppressWarnings(as.numeric(unit_df[[param]]))
  m <- mean(v[which(unit_df[[trt_col]] == ref)], na.rm = TRUE)
  if (!is.finite(m) || m <= 0) return(NULL)
  unit_df[[param]] <- v / m * 100
  unit_df
}

# ── Encoder base64 (pura base R, nessuna dipendenza esterna) ─────────────────
base64_encode_raw <- function(raw_bytes) {
  alphabet <- strsplit("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "")[[1]]
  n   <- length(raw_bytes)
  pad <- (3 - n %% 3) %% 3
  if (pad > 0) raw_bytes <- c(raw_bytes, raw(pad))
  m <- matrix(as.integer(raw_bytes), nrow = 3)
  idx <- rbind(
    bitwShiftR(m[1, ], 2),
    bitwOr(bitwShiftL(bitwAnd(m[1, ], 3L), 4), bitwShiftR(m[2, ], 4)),
    bitwOr(bitwShiftL(bitwAnd(m[2, ], 15L), 2), bitwShiftR(m[3, ], 6)),
    bitwAnd(m[3, ], 63L)
  )
  out <- alphabet[idx + 1]
  out <- matrix(out, nrow = 4)
  if (pad >= 1) out[4, ncol(out)] <- "="
  if (pad == 2) out[3, ncol(out)] <- "="
  paste(out, collapse = "")
}

# ── Estrae l'unità di misura dal nome colonna, es. "Length(cm)" → "cm" ───────
extract_unit <- function(param_name) {
  m <- regmatches(param_name, regexpr("\\(([^)]+)\\)\\s*$", param_name))
  if (length(m) == 0 || m == "") return(NULL)
  sub("^\\((.+)\\)$", "\\1", m)
}

# ── Palette dei trattamenti ──────────────────────────────────────────────────
# npg: ggsci::pal_npg() (Nature Publishing Group), molto usata in figure di biologia.
# okabe: Okabe-Ito senza il nero, distinguibile con deficit della visione dei colori.
# gray: generata sul numero di trattamenti, per la stampa in bianco e nero.
# Oltre il numero di colori disponibili, npg e okabe ricominciano dall'inizio.
PALETTES <- list(
  npg   = c("#E64B35", "#4DBBD5", "#00A087", "#3C5488", "#F39B7F",
            "#8491B4", "#91D1C2", "#DC0000", "#7E6148", "#B09C85"),
  okabe = c("#E69F00", "#56B4E9", "#009E73", "#F0E442",
            "#0072B2", "#D55E00", "#CC79A7", "#999999")
)
DEFAULT_PALETTE <- "npg"

get_palette <- function(name, n) {
  base <- if (identical(name, "gray")) gray.colors(max(n, 1), start = 0.2, end = 0.85)
          else if (!is.null(PALETTES[[name]])) PALETTES[[name]]
          else PALETTES[[DEFAULT_PALETTE]]
  rep_len(adjustcolor(base, alpha.f = 0.8), n)
}

# Etichette del grafico nella lingua dell'interfaccia
chart_labels <- function(tx) {
  list(mean = tx$chart_ylab, value = tx$chart_ylab_value,
       pct = tx$chart_ylab_pct, no_ref = tx$chart_no_ref)
}

# ── Grafico esplorativo (grafica base R): barre, boxplot o punti ─────────────
# Tutto è calcolato sull'unità sperimentale (vasi, se presenti).
draw_chart <- function(df, params, trt_col = "treatment", type = "bar",
                       show_jitter = FALSE, trt_order = NULL, pct = FALSE,
                       palette = DEFAULT_PALETTE, labels = chart_labels(TR$en)) {
  set.seed(1)  # jitter riproducibile: stessi dati, stessa figura
  # Stile fisso "theme_bw": sfondo sempre bianco, indipendente dal tema dell'app,
  # cosi' il file scaricato e' sempre leggibile e stampabile.
  fg       <- "#1A1A1A"          # testo/assi: quasi nero, come theme_bw
  major_gr <- "#E5E5E5"          # griglia major (panel.grid.major)
  minor_gr <- "#F0F0F0"          # griglia minor (panel.grid.minor)
  panel_bg <- "#FFFFFF"          # panel.background: bianco puro
  plot_bg  <- "#FFFFFF"          # plot.background: bianco puro

  # Palette condivisa: stesso trattamento → stesso colore in ogni pannello,
  # anche quando cambia l'ordine
  all_treatments <- sort(unique(as.character(df[[trt_col]])))
  trt_colors <- setNames(get_palette(palette, length(all_treatments)), all_treatments)
  trt_levels <- order_treatments(df[[trt_col]], trt_order)

  par(bg = plot_bg, col.axis = fg, col.lab = fg, col.main = fg, fg = fg,
      font.main = 1, cex.main = 1.4, cex.lab = 1.3, cex.axis = 1.2)

  n_params <- length(params)
  if (n_params > 1) {
    n_col <- 2
    n_row <- ceiling(n_params / n_col)
    par(mfrow = c(n_row, n_col), mar = c(7, 6.5, 3.2, 1.4), mgp = c(4, 0.9, 0))
  } else {
    par(mfrow = c(1, 1), mar = c(7, 6.5, 3.2, 1.4), mgp = c(4, 0.9, 0))
  }

  for (i in seq_along(params)) {
    p   <- params[i]
    unit_df <- collapse_to_unit(df, p, trt_col)
    if (is.null(unit_df)) next

    if (pct) {
      unit_df <- to_pct_of_control(unit_df, p, trt_levels[1], trt_col)
      if (is.null(unit_df)) {
        plot.new()
        title(main = p, cex.main = 1.4, col.main = fg, font.main = 2)
        text(0.5, 0.5, labels$no_ref, col = fg, cex = 1.1)
        next
      }
    }

    agg <- compute_mean_se(unit_df, p, trt_col)
    if (is.null(agg) || !nrow(agg)) next
    agg <- agg[match(intersect(trt_levels, agg$treatment), agg$treatment), ]

    bar_cols <- trt_colors[agg$treatment]
    n_bars   <- nrow(agg)
    x_pos    <- seq(0.7, by = 1.2, length.out = n_bars)  # come barplot(space = 0.2)
    has_se   <- !is.na(agg$se) & agg$se > 0

    # Valori delle unità sperimentali, calcolati prima per includerli nello ylim
    raw_vals <- suppressWarnings(as.numeric(unit_df[[p]]))
    raw_trt  <- as.character(unit_df[[trt_col]])
    ok_pts   <- !is.na(raw_vals) & !is.na(raw_trt)
    pts_vals <- raw_vals[ok_pts]
    pts_trt  <- raw_trt[ok_pts]

    if (type == "bar") {
      ylim_max <- max(agg$mean + agg$se, na.rm = TRUE) * 1.18
      if (show_jitter && length(pts_vals)) {
        ylim_max <- max(ylim_max, max(pts_vals, na.rm = TRUE) * 1.1)
      }
      ylim <- c(0, ylim_max)
    } else {
      # Boxplot e punti: asse sull'intervallo dei dati, per leggere la dispersione
      rng <- range(pts_vals, agg$mean + agg$se, agg$mean - agg$se)
      pad <- if (diff(rng) > 0) diff(rng) * 0.12 else max(abs(rng[1]) * 0.1, 1)
      ylim <- c(if (rng[1] >= 0) max(rng[1] - pad, 0) else rng[1] - pad, rng[2] + pad)
    }

    # 1) pannello vuoto con sfondo bianco (panel.background)
    plot.new()
    plot.window(xlim = c(0.2, n_bars * 1.2 + 0.2), ylim = ylim)
    rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
         col = panel_bg, border = NA)

    # 2) griglia minor + major (sotto i dati, come in ggplot)
    y_major <- pretty(ylim)
    y_major <- y_major[y_major >= ylim[1] & y_major <= ylim[2]]
    y_minor <- (head(y_major, -1) + tail(y_major, -1)) / 2
    abline(h = y_minor, col = minor_gr, lwd = 0.7)
    abline(h = y_major, col = major_gr, lwd = 1)
    if (pct) abline(h = 100, col = fg, lty = 2, lwd = 1)

    draw_se <- function() {
      if (!any(has_se)) return(invisible())
      low <- agg$mean[has_se] - agg$se[has_se]
      if (type == "bar") low <- pmax(low, 0)
      arrows(x0 = x_pos[has_se], y0 = agg$mean[has_se], x1 = x_pos[has_se],
             y1 = agg$mean[has_se] + agg$se[has_se],
             angle = 90, length = 0.08, col = fg, lwd = 1.6)
      arrows(x0 = x_pos[has_se], y0 = agg$mean[has_se], x1 = x_pos[has_se],
             y1 = low, angle = 90, length = 0.08, col = fg, lwd = 1.6)
    }
    # Punti individuali: piccoli, semi-trasparenti, grigio scuro neutro per non
    # competere visivamente con il colore di barre e box.
    draw_jitter <- function() {
      if (!length(pts_vals)) return(invisible())
      jx <- setNames(x_pos, agg$treatment)[pts_trt] + runif(length(pts_trt), -0.13, 0.13)
      points(jx, pts_vals, pch = 21, bg = adjustcolor("#1A1A1A", alpha.f = 0.45),
             col = adjustcolor("#1A1A1A", alpha.f = 0.6), cex = 0.85, lwd = 0.6)
    }

    # 3) dati: la barra d'errore è sopra i punti, sempre ben visibile
    # (solo dove SE > 0: con n = 1 non c'è barra d'errore)
    if (type == "bar") {
      barplot(agg$mean, col = bar_cols, border = "#1A1A1A", lwd = 0.9,
              ylim = ylim, add = TRUE, ylab = "", main = "",
              names.arg = rep("", n_bars), axes = FALSE)
      if (show_jitter) draw_jitter()
      draw_se()
    } else if (type == "box") {
      # Con il jitter i valori estremi sono già tra i punti: niente doppioni
      boxplot(split(pts_vals, factor(pts_trt, levels = agg$treatment)),
              at = x_pos, add = TRUE, axes = FALSE, names = rep("", n_bars),
              col = bar_cols, border = fg, lwd = 0.9, outline = !show_jitter)
      if (show_jitter) draw_jitter()
    } else {
      jx <- setNames(x_pos, agg$treatment)[pts_trt] + runif(length(pts_trt), -0.18, 0.18)
      points(jx, pts_vals, pch = 21, bg = trt_colors[pts_trt], col = fg, cex = 1.3, lwd = 0.7)
      segments(x_pos - 0.32, agg$mean, x_pos + 0.32, agg$mean, col = fg, lwd = 2.4)
      draw_se()
    }

    # Etichetta asse Y con unità di misura tra parentesi quadre, se presente
    unit      <- extract_unit(p)
    ylab_full <- if (pct) paste0(labels$pct, " (", trt_levels[1], ")")
                 else {
                   base <- if (type == "bar") labels$mean else labels$value
                   if (!is.null(unit)) paste0(base, " [", unit, "]") else base
                 }

    # 4) etichette asse X ruotate di 30 gradi (testo posizionato manualmente)
    usr <- par("usr")
    y_off <- (usr[4] - usr[3]) * 0.03
    text(x = x_pos, y = usr[3] - y_off,
         labels = paste0(agg$treatment, " (n=", agg$n, ")"),
         srt = 30, adj = c(1, 1), xpd = TRUE, cex = 1.2, col = fg)

    # 5) assi e bordo pannello (panel.border)
    axis(2, at = y_major, col = fg, col.axis = fg, cex.axis = 1.2, las = 1, mgp = c(4, 0.9, 0))
    box(col = fg, lwd = 1)
    title(ylab = ylab_full, cex.lab = 1.3, col.lab = fg)
    title(main = p, cex.main = 1.4, col.main = fg, font.main = 2)
  }
  par(mfrow = c(1, 1))

  invisible(trt_colors)
}

# Disegna il grafico su file. Stesse dimensioni per tutti i formati.
render_chart_file <- function(spec, path, device = "png", err_msg = "Export failed") {
  n_p   <- length(spec$params)
  n_col <- if (n_p > 1) 2 else 1
  w <- 5.2 * n_col
  h <- 4.6 * ceiling(n_p / n_col)
  # png a 300 dpi: evita la sgranatura visibile quando c'è un solo parametro.
  # pdf con codifica WinAnsi: copre gli accenti e il simbolo dell'euro.
  before <- dev.cur()
  suppressWarnings(switch(device,
    png = png(path, width = w, height = h, units = "in", res = 300),
    pdf = pdf(path, width = w, height = h, useDingbats = FALSE, encoding = "WinAnsi"),
    svg = svg(path, width = w, height = h)))
  # Senza cairo svg() non apre alcun device e avvisa soltanto
  if (dev.cur() == before) stop(err_msg, call. = FALSE)
  tryCatch(do.call(draw_chart, spec), finally = dev.off())
  invisible(path)
}

# ── Parametri numerici disponibili per il grafico (dati wide) ────────────────
get_available_chart_params <- function(df) {
  excl <- c("SampleId", "datetime", "treatment", "replicate", "pot", "plant", "source_file")
  cand <- setdiff(colnames(df), excl)
  cand[vapply(cand, function(c) {
    !all(is.na(suppressWarnings(as.numeric(df[[c]]))))
  }, logical(1))]
}

df_to_csv_string <- function(df, sep = ";") {
  # v1.1: virgolette (stile RFC 4180) solo sui campi che contengono il
  # separatore, virgolette o a capo, così un nome come "N;P" non sposta le colonne
  df[] <- lapply(df, function(x) {
    x <- as.character(x)
    need <- !is.na(x) & grepl(paste0("[", sep, "\"\n]"), x)
    x[need] <- paste0('"', gsub('"', '""', x[need], fixed = TRUE), '"')
    x
  })
  con <- textConnection("out", "w")
  write.table(df, con, sep = sep, row.names = FALSE, quote = FALSE, na = "")
  close(con)
  paste(out, collapse = "\n")
}

# ── UI ───────────────────────────────────────────────────────────────────────
ui <- page_fluid(
  title = "CleanRhizo 🧹",
  theme = bs_theme(
    version       = 5,
    base_font     = "system-ui",
    heading_font  = "system-ui",
    bg            = "#F5F7F5",
    fg            = "#1A1F1A",
    primary       = "#3A6B35",
    secondary     = "#A8C5A0",
    border_radius = "6px"
  ),

  tags$head(tags$style(HTML("
    html, body { padding: 1rem 1.5rem !important; margin: 0 !important; background: #F5F7F5 !important; }
    @media (prefers-color-scheme: dark) {
      html, body { background: #141A13 !important; color: #D8E8D5 !important; }
    }
    h1.title { display: none !important; }
    .wr-card { background: #fff; border: 1px solid #DDE5DB; border-radius: 10px; padding: 1.8rem 2.2rem; margin-bottom: 1.4rem; box-shadow: 0 1px 4px rgba(0,0,0,.05); }
    .app-title    { font-size: 1.75rem; font-weight: 800; color: #1A1F1A; margin-bottom: .15rem; letter-spacing: -.4px; }
    .app-subtitle { font-size: 1.05rem; color: #5A6B58; margin-bottom: 0; }
    .badge-idle  { background: #EAF0E8; color: #4A5E47; }
    .badge-ok    { background: #D4EDDA; color: #1A5C29; }
    .badge-error { background: #FEE2E2; color: #991B1B; }
    .status-badge { display: inline-block; font-size: .92rem; font-weight: 600; padding: .28em .85em; border-radius: 999px; min-width: 7rem; text-align: center; white-space: nowrap; }
    .shiny-html-output:has(.status-badge) { display: inline-block; flex-shrink: 0; }
    .lang-switcher { display: inline-flex; align-items: center; border: 1.5px solid #C5D4C2; border-radius: 6px; overflow: hidden; font-size: .82rem; font-weight: 700; }
    .lang-btn { padding: .32rem .75rem; cursor: pointer; background: #fff; color: #5A6B58; border: none; border-right: 1px solid #C5D4C2; transition: all .12s; user-select: none; }
    /* scheme selector */
    .scheme-grid { display: flex; flex-wrap: wrap; gap: .7rem; margin-bottom: 1.1rem; }
    .scheme-card {
      flex: 1; min-width: 220px; padding: .8rem 1rem;
      border: 1.5px solid #C5D4C2; border-radius: 8px; background: #fff;
      cursor: pointer; transition: all .12s;
    }
    .scheme-card.active { border-color: #3A6B35; background: #EAF4E8; box-shadow: 0 0 0 1px #3A6B35; }
    .scheme-card-title { font-size: .88rem; font-weight: 700; color: #1A3D17; margin-bottom: .25rem; }
    .scheme-card-sub   { font-size: .78rem; color: #5A6B58; font-family: monospace; }
    /* manual segment role assignment */
    .segment-row { display: flex; flex-wrap: wrap; gap: .6rem; align-items: flex-end; margin-bottom: 1rem; }
    .segment-block { display: flex; flex-direction: column; align-items: center; gap: .35rem; }
    .segment-token {
      font-family: monospace; font-size: .92rem; font-weight: 700; color: #1A3D17;
      background: #EAF0E8; border: 1.5px solid #C5D4C2; border-radius: 6px;
      padding: .35rem .7rem; min-width: 2.4rem; text-align: center;
    }
    .segment-sep { font-family: monospace; font-size: .9rem; color: #9CA3AF; padding-bottom: .55rem; }
    .segment-role-select {
      font-size: .76rem; border: 1.5px solid #C5D4C2; border-radius: 5px;
      padding: .25rem .4rem; background: #fff; color: #374151; cursor: pointer;
    }
    .segment-role-select.role-treatment { border-color: #3A6B35; background: #EAF4E8; color: #1A3D17; font-weight: 600; }
    .segment-role-select.role-pot       { border-color: #1D4ED8; background: #EAF0FB; color: #1D3A8A; font-weight: 600; }
    .segment-role-select.role-plant     { border-color: #7C3AED; background: #F5F0FE; color: #4C1D95; font-weight: 600; }
    .manual-warning {
      font-size: .82rem; color: #92400E; background: #FFF7ED; border: 1px solid #FED7AA;
      border-radius: 6px; padding: .6rem .9rem; margin-bottom: 1rem;
    }
    .lang-btn:last-child { border-right: none; }
    .lang-btn.active { background: #3A6B35; color: #fff; }
    .lang-btn:hover:not(.active) { background: #EAF0E8; }
    .privacy-banner { background: #F0F9EF; border: 1px solid #B8DABB; border-radius: 10px; padding: 1rem 1.4rem; margin-bottom: 1.4rem; display: flex; align-items: flex-start; gap: .9rem; }
    .privacy-icon  { font-size: 1.3rem; flex-shrink: 0; line-height: 1.5; }
    .privacy-title { font-size: .8rem; font-weight: 700; color: #14532D; margin-bottom: .2rem; letter-spacing: .04em; text-transform: uppercase; }
    .privacy-body  { font-size: .82rem; color: #166534; margin: 0; line-height: 1.55; }
    /* naming guide */
    .guide-banner {
      background: #FFFBEB; border: 1px solid #FDE68A; border-radius: 10px;
      padding: 1.1rem 1.4rem; margin-bottom: 1.4rem;
    }
    .guide-title { font-size: .85rem; font-weight: 700; color: #92400E; margin-bottom: .5rem; }
    .guide-intro { font-size: .82rem; color: #78350F; margin-bottom: .9rem; line-height: 1.55; }
    .guide-cases { display: flex; flex-wrap: wrap; gap: 1rem; margin-bottom: .9rem; }
    .guide-case {
      flex: 1; min-width: 260px; background: #fff; border: 1px solid #FDE68A;
      border-radius: 8px; padding: .9rem 1.1rem;
    }
    .guide-case-title { font-size: .82rem; font-weight: 700; color: #92400E; margin-bottom: .4rem; }
    .guide-case-body  { font-size: .8rem; color: #57534E; margin-bottom: .6rem; line-height: 1.5; }
    .guide-case-ex {
      font-family: monospace; font-size: .78rem; color: #166534; background: #F0FDF4;
      border: 1px solid #BBF7D0; border-radius: 5px; padding: .35rem .6rem; margin-top: .3rem;
    }
    .guide-case-ex-bad {
      color: #9F1239; background: #FFF1F2; border-color: #FECDD3;
    }
    .section-label { font-size: .88rem; font-weight: 700; letter-spacing: .07em; text-transform: uppercase; color: #5A6B58; margin-bottom: .75rem; }
    .file-chip { display: inline-block; font-size: .78rem; background: #EAF0E8; border: 1px solid #C5D4C2; border-radius: 4px; padding: .2rem .6rem; color: #3A6B35; font-weight: 600; margin-top: .5rem; }
    .col-grid { display: flex; flex-wrap: wrap; gap: .45rem; margin-bottom: .9rem; }
    .col-toggle { display: inline-flex; align-items: center; gap: .35rem; padding: .42rem .9rem; border-radius: 999px; border: 1.5px solid #C5D4C2; background: #fff; font-size: .92rem; font-weight: 500; color: #374151; cursor: pointer; transition: all .12s; user-select: none; }
    .col-toggle.active  { border-color: #3A6B35; background: #EAF0E8; color: #1A3D17; }
    .col-toggle.active::before { content: '✓'; font-size: .82rem; color: #3A6B35; font-weight: 700; }
    .col-toggle.excluded { border-color: #DDE5DB; background: #F9FAF9; color: #9CA3AF; text-decoration: line-through; }
    .toggle-meta { font-size: .8rem; color: #5A6B58; margin-top: .35rem; margin-bottom: 0; }
    .toggle-actions { display: flex; gap: .7rem; margin-bottom: .8rem; }
    .link-btn { background: none; border: none; padding: 0; font-size: .92rem; color: #3A6B35; font-weight: 600; cursor: pointer; text-decoration: underline; }
    .link-btn:hover { color: #2A5027; }
    .shiny-input-container { width: 100% !important; }
    .form-group { margin-bottom: 0; }
    #clean_btn, #trt_btn {
      border: none; color: #fff; font-weight: 700; font-size: .95rem;
      padding: .58rem 1.6rem; border-radius: 6px; transition: background .15s;
    }
    #clean_btn { background: #3A6B35; } #clean_btn:hover { background: #2A5027; }
    #trt_btn   { background: #1D4ED8; } #trt_btn:hover   { background: #1E40AF; }
    .dl-wrap .btn { border: 1.5px solid #3A6B35; color: #3A6B35; background: transparent; font-weight: 600; font-size: 1.05rem; padding: .58rem 1.6rem; border-radius: 6px; transition: all .15s; }
    .dl-wrap .btn:hover { background: #EAF0E8; }
    .stats-strip { display: flex; flex-wrap: wrap; gap: 2rem; padding: .9rem 1.3rem; background: #EAF4E8; border-radius: 6px; border: 1px solid #B8DABB; margin-bottom: 1.3rem; }
    .stat-item { display: flex; flex-direction: column; }
    .stat-val  { font-size: 1.5rem; font-weight: 800; color: #3A6B35; line-height: 1; }
    .stat-lbl  { font-size: .85rem; color: #5A6B58; margin-top: .2rem; }
    .preview-wrap { overflow-x: auto; overflow-y: auto; max-height: 340px; border-radius: 6px; border: 1px solid #DDE5DB; }
    .preview-wrap thead th { background: #EAF0E8; font-weight: 700; color: #1A3D17; border-bottom: 2px solid #C5D4C2; padding: .5rem .75rem; position: sticky; top: 0; z-index: 1; }
    .preview-wrap table { font-size: .95rem !important; margin-bottom: 0; white-space: nowrap; }
    .preview-wrap tbody td { padding: .4rem .75rem; color: #374151; border-bottom: 1px solid #F0F4EF; }
    .preview-wrap tbody tr:last-child td { border-bottom: none; }
    .rename-chips { display: flex; flex-wrap: wrap; gap: .4rem; margin-bottom: .5rem; }
    .rename-chip { font-size: .78rem; padding: .22rem .6rem; border-radius: 4px; background: #FFF7ED; border: 1px solid #FED7AA; color: #92400E; font-family: monospace; }
    .rename-chip .arr { color: #9CA3AF; margin: 0 .25rem; }
    .rename-chip .to  { color: #1A3D17; font-weight: 700; }
    .trt-table { width: 100%; border-collapse: collapse; margin-bottom: 1rem; font-size: .86rem; }
    .trt-table thead th { background: #EAF0E8; font-weight: 700; color: #1A3D17; border-bottom: 2px solid #C5D4C2; padding: .45rem .75rem; text-align: left; }
    .trt-table tbody td { padding: .35rem .75rem; border-bottom: 1px solid #F0F4EF; vertical-align: middle; }
    .trt-table tbody tr:last-child td { border-bottom: none; }
    .trt-table tbody tr:hover td { background: #F5FAF4; }
    .trt-input { width: 100%; border: 1.5px solid #C5D4C2; border-radius: 5px; padding: .28rem .55rem; font-size: .84rem; color: #1A1F1A; outline: none; transition: border-color .12s; background: #fff; }
    .trt-input:focus { border-color: #3A6B35; }
    .trt-detected { font-size: .82rem; color: #3A6B35; font-weight: 600; }
    .trt-table tbody td code { color: #374151; background: #F3F4F6; padding: .1rem .4rem; border-radius: 3px; font-size: .8rem; }
    .section-divider { border: none; border-top: 1px dashed #C5D4C2; margin: 1.3rem 0; }
    .pivot-toggle { display: flex; align-items: center; gap: .85rem; padding: 1rem 1.2rem; border-radius: 8px; border: 1.5px solid #DDE5DB; background: #FAFAFA; margin-bottom: 1.2rem; cursor: pointer; transition: all .12s; }
    .pivot-toggle:hover { border-color: #7C3AED; background: #F5F3FF; }
    .pivot-toggle.on    { border-color: #7C3AED; background: #F5F3FF; }
    .pivot-switch { width: 2.6rem; height: 1.4rem; border-radius: 999px; background: #C5D4C2; position: relative; flex-shrink: 0; transition: background .15s; }
    .pivot-toggle.on .pivot-switch { background: #7C3AED; }
    .pivot-switch::after { content: ''; position: absolute; top: .18rem; left: .18rem; width: 1.04rem; height: 1.04rem; border-radius: 50%; background: #fff; transition: left .15s; }
    .pivot-toggle.on .pivot-switch::after { left: 1.38rem; }
    .pivot-label { font-size: 1rem; font-weight: 600; color: #374151; }
    .pivot-sub   { font-size: .88rem; color: #5A6B58; margin-top: .15rem; }
    /* chart panel */
    .chart-param-grid { display: flex; flex-wrap: wrap; gap: .5rem; margin-bottom: 1rem; }
    .chart-param-toggle {
      display: inline-flex; align-items: center; gap: .4rem; padding: .42rem .9rem;
      border-radius: 999px; border: 1.5px solid #C5D4C2; background: #fff;
      font-size: .92rem; font-weight: 500; color: #374151;
      cursor: pointer; transition: all .12s; user-select: none;
    }
    .chart-param-toggle.active { border-color: #0E7490; background: #E0F4F8; color: #0C4A5C; }
    .chart-param-toggle.active::before { content: '✓'; font-size: .82rem; color: #0E7490; font-weight: 700; }
    .chart-param-toggle.excluded { border-color: #DDE5DB; background: #F9FAF9; color: #9CA3AF; }
    #chart_btn {
      border: none; color: #fff; font-weight: 700; font-size: .95rem;
      padding: .58rem 1.6rem; border-radius: 6px; background: #0E7490; transition: background .15s;
    }
    #chart_btn:hover { background: #0C5E76; }
    .chart-wrap {
      background: #fff; border-radius: 6px; border: 1px solid #DDE5DB;
      padding: 1rem; margin-top: 1rem;
    }
    .chart-wrap img { width: 100%; height: auto; display: block; border-radius: 4px; }
    .chart-hint { font-size: .82rem; color: #5A6B58; margin-bottom: 1rem; }
    .col-toggle.col-derived { border-style: dashed; }
    .csv-sep-row { display: flex; align-items: center; gap: .7rem; flex-wrap: wrap; margin-top: 1.1rem; }
    .csv-sep-lbl { font-size: .9rem; font-weight: 600; color: #5A6B58; }
    .csv-sep-hint { font-size: .8rem; color: #5A6B58; }
    .seg-switch { display: inline-flex; border: 1.5px solid #C5D4C2; border-radius: 6px; overflow: hidden; }
    .seg-btn { padding: .3rem .75rem; font-size: .85rem; font-weight: 600; background: #fff; color: #5A6B58; border: none; border-right: 1px solid #C5D4C2; cursor: pointer; }
    .seg-btn:last-child { border-right: none; }
    .seg-btn.active { background: #3A6B35; color: #fff; }
    .qc-table td { vertical-align: top; }
    .qc-table td:last-child { white-space: normal; min-width: 14rem; }
    .qc-table tr.qc-excluded td { opacity: .45; }
    .qc-include { width: 1.05rem; height: 1.05rem; cursor: pointer; accent-color: #3A6B35; }
    .qc-chip { display: inline-block; font-size: .76rem; padding: .1rem .45rem; margin: .1rem .25rem .1rem 0; border-radius: 4px; border: 1px solid #FED7AA; background: #FFF7ED; color: #92400E; }
    .qc-chip-duplicate { border-color: #BFDBFE; background: #EFF6FF; color: #1E40AF; }
    .qc-chip-outlier   { border-color: #DDD6FE; background: #F5F3FF; color: #5B21B6; }
    .qc-ok { font-size: .92rem; font-weight: 600; color: #166534; margin-bottom: 1rem; }
    .qc-dups { display: flex; align-items: center; gap: .8rem; flex-wrap: wrap; margin-bottom: 1rem; }
    .qc-dups .chart-hint { margin-bottom: 0; }
    #qc_drop_dups { border: 1.5px solid #1D4ED8; color: #1D4ED8; background: transparent; font-weight: 600; border-radius: 6px; }
    #example_btn { display: inline-block; margin-top: .6rem; font-size: .92rem; font-weight: 600; color: #3A6B35; }
    .chart-type-grid { display: flex; flex-wrap: wrap; gap: .6rem; margin-bottom: 1rem; }
    .chart-type-card {
      flex: 1; min-width: 150px; padding: .6rem .9rem; text-align: left;
      border: 1.5px solid #C5D4C2; border-radius: 8px; background: #fff;
      cursor: pointer; transition: all .12s;
    }
    .chart-type-card.active { border-color: #0E7490; background: #E0F4F8; box-shadow: 0 0 0 1px #0E7490; }
    .chart-type-title { font-size: .9rem; font-weight: 700; color: #0C4A5C; }
    .chart-type-sub   { font-size: .78rem; color: #5A6B58; margin-top: .1rem; }
    .palette-swatches { display: flex; gap: 3px; margin-top: .4rem; }
    .palette-swatch { width: 1rem; height: .7rem; border-radius: 2px; border: 1px solid rgba(0,0,0,.25); }
    .trt-order-list { display: flex; flex-wrap: wrap; gap: .5rem; margin-bottom: .4rem; }
    .trt-order-item {
      display: inline-flex; align-items: center; gap: .25rem; padding: .28rem .4rem;
      border: 1.5px solid #C5D4C2; border-radius: 8px; background: #fff;
      font-size: .9rem; font-weight: 500; color: #374151;
    }
    .trt-move { border: none; background: none; color: #0E7490; cursor: pointer; padding: .1rem .3rem; font-size: .75rem; line-height: 1; }
    .trt-order-item:first-child .trt-move-left,
    .trt-order-item:last-child  .trt-move-right { visibility: hidden; }
    /* ── dark mode ─────────────────────────────────────────────────────────── */
    body.dark, body.dark html { background: #141A13 !important; color: #D8E8D5 !important; }
    body.dark .wr-card { background: #1E261D; border-color: #334430; box-shadow: 0 1px 6px rgba(0,0,0,.3); }
    body.dark .app-title { color: #E8F4E5; }
    body.dark .app-subtitle { color: #7A9975; }
    body.dark .section-label { color: #7A9975; }
    body.dark .section-divider { border-color: #334430; }
    body.dark .badge-idle  { background: #253023; color: #7A9975; }
    body.dark .badge-ok    { background: #1A3D22; color: #6FCF7F; }
    body.dark .badge-error { background: #3D1A1A; color: #F87171; }
    body.dark .lang-switcher { border-color: #334430; }
    body.dark .scheme-card { background: #1E261D; border-color: #334430; }
    body.dark .scheme-card.active { border-color: #5A9B55; background: #1E3A1A; box-shadow: 0 0 0 1px #5A9B55; }
    body.dark .scheme-card-title { color: #C5D8C2; }
    body.dark .scheme-card-sub   { color: #7A9975; }
    body.dark .segment-token { background: #1E3A1A; border-color: #334430; color: #C5D8C2; }
    body.dark .segment-sep   { color: #5A6B58; }
    body.dark .segment-role-select { background: #1E261D; border-color: #334430; color: #B8D0B5; }
    body.dark .segment-role-select.role-treatment { border-color: #5A9B55; background: #1E3A1A; color: #A8E0A0; }
    body.dark .segment-role-select.role-pot       { border-color: #3B5FE0; background: #16203D; color: #93B4FA; }
    body.dark .segment-role-select.role-plant     { border-color: #9F6BF0; background: #261A3D; color: #CBB2F5; }
    body.dark .manual-warning { background: #2D2010; border-color: #5A3E1A; color: #D4A050; }
    body.dark .lang-btn { background: #1E261D; color: #7A9975; border-color: #334430; }
    body.dark .lang-btn.active { background: #3A6B35; color: #fff; }
    body.dark .lang-btn:hover:not(.active) { background: #253023; color: #D8E8D5; }
    body.dark .privacy-banner { background: #1A2D1A; border-color: #2A4A2A; }
    body.dark .privacy-title { color: #6FCF7F; }
    body.dark .privacy-body  { color: #7A9975; }
    body.dark .guide-banner { background: #2D2410; border-color: #5A4A1A; }
    body.dark .guide-title  { color: #FBBF24; }
    body.dark .guide-intro  { color: #D4B870; }
    body.dark .guide-case   { background: #1E261D; border-color: #5A4A1A; }
    body.dark .guide-case-title { color: #FBBF24; }
    body.dark .guide-case-body  { color: #B8D0B5; }
    body.dark .guide-case-ex    { background: #1A2D1A; border-color: #2A4A2A; color: #6FCF7F; }
    body.dark .guide-case-ex-bad { background: #3D1A20; border-color: #5A2A35; color: #FCA5A5; }
    body.dark .file-chip { background: #253023; border-color: #334430; color: #6FCF7F; }
    body.dark .col-toggle { background: #1E261D; border-color: #334430; color: #C5D8C2; }
    body.dark .col-toggle.active { border-color: #5A9B55; background: #1E3A1A; color: #A8E0A0; }
    body.dark .col-toggle.excluded { background: #161E15; color: #4A5E47; }
    body.dark .toggle-meta { color: #7A9975; }
    body.dark .link-btn { color: #6FCF7F; }
    body.dark .link-btn:hover { color: #A8E0A0; }
    body.dark #clean_btn { background: #3A6B35; } body.dark #clean_btn:hover { background: #4A8A44; }
    body.dark #trt_btn   { background: #1D4ED8; } body.dark #trt_btn:hover   { background: #2563EB; }
    body.dark .dl-wrap .btn { border-color: #5A9B55; color: #6FCF7F; }
    body.dark .dl-wrap .btn:hover { background: #1E3A1A; }
    body.dark .stats-strip { background: #1A2D1A; border-color: #2A4A2A; }
    body.dark .stat-val { color: #6FCF7F; }
    body.dark .stat-lbl { color: #7A9975; }
    body.dark .preview-wrap { border-color: #334430; background: #1E261D; }
    body.dark .preview-wrap thead th { background: #253023; color: #C5D8C2; border-color: #334430; }
    body.dark .preview-wrap tbody td { background: #1E261D; color: #B8D0B5; border-color: #2A3528; }
    body.dark .preview-wrap tbody tr:hover td { background: #243426; }
    body.dark .preview-wrap table { background: #1E261D; }
    body.dark .rename-chip { background: #2D2010; border-color: #5A3E1A; color: #D4A050; }
    body.dark .rename-chip .to { color: #6FCF7F; }
    body.dark .trt-table thead th { background: #253023; color: #C5D8C2; border-color: #334430; }
    body.dark .trt-table tbody td { border-color: #253023; color: #B8D0B5; }
    body.dark .trt-table tbody tr:hover td { background: #1E2E1D; }
    body.dark .trt-detected { color: #6FCF7F; }
    body.dark .trt-table tbody td code { color: #C5D8C2; background: #161E15; }
    body.dark .trt-input { background: #253023; border-color: #334430; color: #D8E8D5; }
    body.dark .trt-input:focus { border-color: #5A9B55; }
    body.dark .pivot-toggle { background: #1E261D; border-color: #334430; }
    body.dark .pivot-toggle:hover, body.dark .pivot-toggle.on { border-color: #7C3AED; background: #1E1A2D; }
    body.dark .pivot-switch { background: #334430; }
    body.dark .pivot-label { color: #D8E8D5; }
    body.dark .pivot-sub   { color: #7A9975; }
    body.dark .chart-param-toggle { background: #1E261D; border-color: #334430; color: #C5D8C2; }
    body.dark .chart-param-toggle.active { border-color: #22B8CF; background: #122A30; color: #67E8F9; }
    body.dark .chart-param-toggle.excluded { background: #161E15; color: #4A5E47; }
    body.dark #chart_btn { background: #0E7490; } body.dark #chart_btn:hover { background: #155E75; }
    body.dark .chart-wrap { background: #1E261D; border-color: #334430; }
    body.dark .chart-hint { color: #7A9975; }
    body.dark #example_btn { color: #6FCF7F; }
    body.dark .csv-sep-lbl, body.dark .csv-sep-hint { color: #7A9975; }
    body.dark .seg-switch { border-color: #334430; }
    body.dark .seg-btn { background: #1E261D; color: #7A9975; border-color: #334430; }
    body.dark .seg-btn.active { background: #3A6B35; color: #fff; }
    body.dark .qc-chip { background: #2D2010; border-color: #5A3E1A; color: #D4A050; }
    body.dark .qc-chip-duplicate { background: #16203D; border-color: #3B5FE0; color: #93B4FA; }
    body.dark .qc-chip-outlier   { background: #261A3D; border-color: #9F6BF0; color: #CBB2F5; }
    body.dark .qc-ok { color: #6FCF7F; }
    body.dark #qc_drop_dups { border-color: #3B5FE0; color: #93B4FA; }
    body.dark .chart-type-card { background: #1E261D; border-color: #334430; }
    body.dark .chart-type-card.active { border-color: #22B8CF; background: #122A30; box-shadow: 0 0 0 1px #22B8CF; }
    body.dark .chart-type-title { color: #67E8F9; }
    body.dark .chart-type-sub   { color: #7A9975; }
    body.dark .trt-order-item { background: #1E261D; border-color: #334430; color: #C5D8C2; }
    body.dark .trt-move { color: #67E8F9; }
    body.dark .shiny-table-output table,
    body.dark table.table,
    body.dark table {
      background: #1E261D !important;
      color: #B8D0B5 !important;
    }
    body.dark table.table > :not(caption) > * > * { background: #1E261D !important; color: #B8D0B5 !important; }
    /* input file in dark */
    body.dark .form-control, body.dark .form-select, body.dark input[type=text] {
      background: #253023 !important; border-color: #334430 !important; color: #D8E8D5 !important;
    }
    body.dark .input-group-text { background: #334430 !important; border-color: #3D5438 !important; color: #7A9975 !important; }
  "))),

  tags$script(HTML("
    // ── Auto-resize: comunica l'altezza reale del contenuto alla pagina
    // Quarto genitore, così l'iframe shinylive si allunga invece di avere
    // uno scroll interno quando il contenuto cresce con gli step.
    (function() {
      function sendHeight() {
        var h = document.body.scrollHeight;
        window.parent.postMessage({ type: 'cleanrhizo-resize', height: h }, '*');
      }
      var ro = new ResizeObserver(function() { sendHeight(); });
      ro.observe(document.body);
      // invio iniziale e dopo un breve delay per catturare il primo render completo
      sendHeight();
      setTimeout(sendHeight, 300);
      setTimeout(sendHeight, 1000);
    })();

    // ── Dark mode: segue automaticamente le preferenze del sistema ───────────
    (function() {
      var mq = window.matchMedia('(prefers-color-scheme: dark)');
      function applyDark(on) { document.body.classList.toggle('dark', on); }
      applyDark(mq.matches);
      mq.addEventListener('change', function(e) { applyDark(e.matches); });
    })();

    // ── Preferenze ricordate in questo browser (mai i dati del file) ─────────
    var PREF_KEY = 'cleanrhizo.prefs';
    function loadPrefs() {
      try { return JSON.parse(window.localStorage.getItem(PREF_KEY)) || {}; } catch (e) { return {}; }
    }
    function savePref(key, value) {
      try {
        var p = loadPrefs(); p[key] = value;
        window.localStorage.setItem(PREF_KEY, JSON.stringify(p));
      } catch (e) {}
    }
    $(document).on('shiny:connected', function() {
      var p = loadPrefs();
      if (['en', 'it', 'es', 'fr'].indexOf(p.lang) >= 0) setLang(p.lang);
      if ([1, 2, 3].indexOf(p.scheme) >= 0) Shiny.setInputValue('sampleid_scheme', p.scheme, {priority: 'event'});
      if (['npg', 'okabe', 'gray'].indexOf(p.palette) >= 0) Shiny.setInputValue('chart_palette', p.palette);
      if (['semicolon', 'comma'].indexOf(p.csv_sep) >= 0) Shiny.setInputValue('csv_sep', p.csv_sep);
    });

    function setLang(lang) {
      document.querySelectorAll('.lang-btn').forEach(function(b) {
        b.classList.toggle('active', b.getAttribute('data-lang') === lang);
      });
      Shiny.setInputValue('ui_lang', lang, {priority: 'event'});
      savePref('lang', lang);
    }

    function setScheme(el, levels) {
      document.querySelectorAll('.scheme-card').forEach(function(c) {
        c.classList.toggle('active', c === el);
      });
      Shiny.setInputValue('sampleid_scheme', levels, {priority: 'event'});
      savePref('scheme', levels);
    }

    function setCsvSep(el, value) {
      el.parentNode.querySelectorAll('.seg-btn').forEach(function(b) {
        b.classList.toggle('active', b === el);
      });
      Shiny.setInputValue('csv_sep', value, {priority: 'event'});
      savePref('csv_sep', value);
    }

    function toggleQc(el) {
      var row = el.closest('tr');
      if (row) row.classList.toggle('qc-excluded', !el.checked);
      Shiny.setInputValue('qc_toggle', {row: parseInt(el.getAttribute('data-row'), 10), include: el.checked},
                          {priority: 'event'});
    }

    function toggleQcShowAll() {
      var el = document.getElementById('qc-show-all-toggle');
      var on = el.classList.toggle('on');
      Shiny.setInputValue('qc_show_all', on, {priority: 'event'});
    }

    function updateSegmentRole(sel) {
      sel.classList.remove('role-treatment', 'role-pot', 'role-plant');
      var v = sel.value;
      if (v === 'Treatment') sel.classList.add('role-treatment');
      if (v === 'Pot')       sel.classList.add('role-pot');
      if (v === 'Plant')     sel.classList.add('role-plant');

      var roles = [];
      document.querySelectorAll('.segment-role-select').forEach(function(s) {
        roles.push(s.value);
      });
      Shiny.setInputValue('manual_roles', roles, {priority: 'event'});
    }

    Shiny.addCustomMessageHandler('updateBadge', function(msg) {
      var el = document.getElementById('status_badge_el');
      if (!el) return;
      el.textContent = msg.text;
      el.className = 'status-badge ' + msg.cls;
    });

    Shiny.addCustomMessageHandler('downloadCSV', function(msg) {
      var blob = new Blob([msg.content], {type: 'text/csv;charset=utf-8;'});
      var link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = msg.filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });

    Shiny.addCustomMessageHandler('updateColMeta', function(msg) {
      var el = document.getElementById('col-meta');
      if (el) el.textContent = msg.text;
    });

    function toggleCol(el) { el.classList.toggle('active'); el.classList.toggle('excluded'); updateMeta(); }

    function setAll(state) {
      document.querySelectorAll('.col-toggle').forEach(function(el) {
        el.classList.toggle('active', state); el.classList.toggle('excluded', !state);
      });
      updateMeta();
    }

    function updateMeta() {
      var active = document.querySelectorAll('.col-toggle.active').length;
      var total  = document.querySelectorAll('.col-toggle').length;
      var sel = [];
      document.querySelectorAll('.col-toggle.active').forEach(function(t) { sel.push(t.getAttribute('data-col')); });
      Shiny.setInputValue('selected_cols',    sel,    {priority: 'event'});
      Shiny.setInputValue('active_col_count', active, {priority: 'event'});
    }

    function togglePivot() {
      var el = document.getElementById('pivot-toggle');
      var on = el.classList.toggle('on');
      Shiny.setInputValue('pivot_long', on, {priority: 'event'});
    }

    function toggleJitter() {
      var el = document.getElementById('jitter-toggle');
      var on = el.classList.toggle('on');
      Shiny.setInputValue('show_jitter', on, {priority: 'event'});
    }

    function togglePct() {
      var el = document.getElementById('pct-toggle');
      var on = el.classList.toggle('on');
      Shiny.setInputValue('show_pct', on, {priority: 'event'});
    }

    function setChartChoice(el, input, value) {
      el.parentNode.querySelectorAll('.chart-type-card').forEach(function(c) {
        c.classList.toggle('active', c === el);
      });
      Shiny.setInputValue(input, value, {priority: 'event'});
      if (input === 'chart_palette') savePref('palette', value);
    }

    // Sposta l'elemento vicino, non quello cliccato: il pulsante resta a fuoco.
    function moveTrt(btn, dir) {
      var item = btn.closest('.trt-order-item');
      var list = item.parentNode;
      if (dir < 0 && item.previousElementSibling) {
        list.insertBefore(item.previousElementSibling, item.nextElementSibling);
      }
      if (dir > 0 && item.nextElementSibling) {
        list.insertBefore(item.nextElementSibling, item);
      }
      var order = [];
      list.querySelectorAll('.trt-order-item').forEach(function(t) {
        order.push(t.getAttribute('data-trt'));
      });
      Shiny.setInputValue('trt_order', order, {priority: 'event'});
    }

    function toggleChartParam(el) {
      el.classList.toggle('active');
      el.classList.toggle('excluded');
      var sel = [];
      document.querySelectorAll('.chart-param-toggle.active').forEach(function(t) {
        sel.push(t.getAttribute('data-param'));
      });
      Shiny.setInputValue('chart_params', sel, {priority: 'event'});
    }

    Shiny.addCustomMessageHandler('downloadFile', function(msg) {
      var link = document.createElement('a');
      link.href = 'data:' + msg.mime + ';base64,' + msg.data;
      link.download = msg.filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });

    $(document).on('shiny:value', function(e) {
      if (e.name === 'col_selector_panel') setTimeout(updateMeta, 50);
    });
  ")),

  # ── Header ────────────────────────────────────────────────────────────────
  div(class = "wr-card",
    div(style = "display:flex; align-items:center; justify-content:space-between; flex-wrap:nowrap; gap:.5rem;",
      div(class = "app-title", "CleanRhizo 🧹"),
      div(style = "display:flex; align-items:center; gap:.8rem; flex-wrap:nowrap; flex-shrink:0;",
        tags$span(id = "status_badge_el", class = "status-badge badge-idle", ""),
        div(style = "flex-shrink:0;", class = "lang-switcher",
          tags$button(class = "lang-btn active", `data-lang` = "en", onclick = "setLang('en')", "EN"),
          tags$button(class = "lang-btn",        `data-lang` = "it", onclick = "setLang('it')", "IT"),
          tags$button(class = "lang-btn",        `data-lang` = "es", onclick = "setLang('es')", "ES"),
          tags$button(class = "lang-btn",        `data-lang` = "fr", onclick = "setLang('fr')", "FR")
        )
      )
    ),
    uiOutput("app_subtitle")
  ),

  uiOutput("privacy_banner"),
  uiOutput("guide_banner"),
  uiOutput("step1_panel"),
  uiOutput("col_selector_panel"),
  uiOutput("step3_panel"),
  uiOutput("preview_panel"),
  uiOutput("treatment_panel"),
  uiOutput("qc_panel"),
  uiOutput("pivot_panel"),
  uiOutput("summary_panel"),
  uiOutput("error_panel"),
  uiOutput("chart_panel"),

  hr(class = "section-divider"),
  div(style = "text-align:center; font-size:.9rem; color:#5A6B58; padding:.4rem 0 1.2rem;",
    uiOutput("app_credits")
  )
)

# ── Server ───────────────────────────────────────────────────────────────────
server <- function(input, output, session) {

  rv <- reactiveValues(
    df_raw    = NULL, df_clean = NULL, df_trt = NULL, df_final = NULL,
    error     = NULL, base_name = NULL, chart_png_b64 = NULL,
    chart_spec = NULL,  # argomenti dell'ultimo grafico, riusati per PDF e SVG
    is_example = FALSE, # TRUE quando i dati caricati sono quelli di esempio
    upload_n  = 0L,   # contatore upload: rende univoci gli ID dei campi trattamento
    excluded  = integer(),  # righe escluse al controllo qualità (posizione nei dati)
    qc_version = 0L,  # ridisegna la tabella QC dopo le azioni di gruppo
    sel_cols  = NULL  # ultima selezione colonne, conservata ai re-render
  )

  # Schema del nome campione: lo sceglie l'utente, o i dati di esempio
  scheme <- reactiveVal(1)
  observeEvent(input$sampleid_scheme, { scheme(input$sampleid_scheme) }, priority = 10)

  lang <- reactive({ if (is.null(input$ui_lang)) "en" else input$ui_lang })
  t    <- reactive({ TR[[lang()]] })

  # Separatore di tutti i CSV scaricati
  csv_sep <- reactive({ if (identical(input$csv_sep, "comma")) "," else ";" })

  output$app_subtitle <- renderUI({
    tx <- t()
    tagList(
      p(class = "app-subtitle", tx$app_subtitle, " ",
        tags$a(href = "https://www.regentinstruments.com/assets/winrhizo_mostrecent.html",
               target = "_blank",
               style = "color:#3A6B35;font-weight:700;text-decoration:underline;",
               "WinRhizo — Regent Instruments.")),
      p(class = "app-subtitle", style = "font-size:.88rem;color:#9CA3AF;margin-top:.1rem;",
        tx$app_descr)
    )
  })

  output$privacy_banner <- renderUI({
    tx <- t()
    div(class = "privacy-banner",
      div(class = "privacy-icon", "🔒"),
      div(div(class = "privacy-title", tx$privacy_title),
          p(class = "privacy-body", tx$privacy_body))
    )
  })

  output$guide_banner <- renderUI({
    tx <- t()
    div(class = "guide-banner",
      div(class = "guide-title", tx$guide_title),
      p(class = "guide-intro", tx$guide_intro),
      div(class = "guide-cases",
        div(class = "guide-case",
          div(class = "guide-case-title", tx$guide_case1_title),
          p(class = "guide-case-body", tx$guide_case1_body),
          div(class = "guide-case-ex", tx$guide_case1_ex1)
        ),
        div(class = "guide-case",
          div(class = "guide-case-title", tx$guide_case2_title),
          p(class = "guide-case-body", tx$guide_case2_body),
          div(class = "guide-case-ex", tx$guide_case2_ex1),
          div(class = "guide-case-ex", style = "margin-top:.3rem;", tx$guide_case2_ex2)
        ),
        div(class = "guide-case",
          div(class = "guide-case-title", tx$guide_why_title),
          p(class = "guide-case-body", tx$guide_why_body),
          div(class = "guide-case-ex guide-case-ex-bad",  tx$guide_why_ex1),
          div(class = "guide-case-ex", style = "margin-top:.3rem;", tx$guide_why_ex2)
        )
      )
    )
  })

  output$app_credits <- renderUI({
    cr <- t()$credits
    tagList(
      cr$pre,
      tags$a(href = "https://www.mauromaver.eu", target = "_blank",
             style = "color:#3A6B35; font-weight:700; text-decoration:underline;", "Mauro Maver"),
      " · ",
      tags$span(style = "color:#9CA3AF; font-size:.88rem;", "v.1.3"),
      cr$bug,
      tags$a(href = "https://github.com/Stramon1um", target = "_blank",
             style = "color:#3A6B35; font-weight:600; text-decoration:underline;", "GitHub"),
      cr$or,
      tags$a(href = "mailto:mauro.maver@univr.it",
             style = "color:#3A6B35; font-weight:600; text-decoration:underline;", cr$mail),
      " 😊"
    )
  })

  # ── Step 1 ────────────────────────────────────────────────────────────────
  output$step1_panel <- renderUI({
    tx <- t()
    div(class = "wr-card",
      p(class = "section-label", tx$step1),
      fileInput("file_in", label = NULL, accept = c(".txt", "text/plain"), multiple = TRUE,
                placeholder = tx$file_placeholder, buttonLabel = tx$file_btn),
      actionLink("example_btn", tx$example_btn, icon = icon("seedling")),
      uiOutput("file_info_chip")
    )
  })

  # Uno o più file; con più file il nome di base è quello del primo + "_merged"
  load_data <- function(paths, names, is_example = FALSE) {
    rv$df_raw <- rv$df_clean <- rv$df_trt <- rv$df_final <- rv$error <- rv$chart_png_b64 <- NULL
    rv$upload_n <- rv$upload_n + 1L
    rv$sel_cols <- NULL
    rv$excluded <- integer()
    rv$is_example <- is_example
    tryCatch({
      rv$df_raw    <- read_winrhizo_files(paths, names)
      base         <- sub("\\.[^.]+$", "", names[1])
      rv$base_name <- if (length(paths) > 1) paste0(base, "_merged") else base
    }, error = function(e) rv$error <- conditionMessage(e))
  }

  observeEvent(input$file_in, {
    load_data(input$file_in$datapath, input$file_in$name)
  })

  observeEvent(input$example_btn, {
    f <- tempfile(fileext = ".txt")
    writeLines(EXAMPLE_WINRHIZO, f)
    scheme(EXAMPLE_SCHEME)
    load_data(f, "example_winrhizo.txt", is_example = TRUE)
    unlink(f)
  })

  output$file_info_chip <- renderUI({
    req(rv$df_raw)
    tx <- t()
    df <- rv$df_raw
    n_files <- attr(df, "n_files")
    missing <- attr(df, "missing_cols")
    # colonne lette dai file, senza quelle aggiunte dall'app
    n_cols  <- sum(!colnames(df) %in% c(names(DERIVED_TRAITS), "source_file"))
    tagList(
      div(class = "file-chip", tx$file_info(nrow(df), n_cols)),
      if (isTRUE(n_files > 1)) div(class = "file-chip", style = "margin-left:.4rem;", tx$files_merged(n_files)),
      if (length(missing)) div(class = "manual-warning", style = "margin:.6rem 0 0;",
        icon("triangle-exclamation"), " ", tx$files_cols_warning, " ", paste(missing, collapse = ", ")),
      if (rv$is_example) p(class = "chart-hint", style = "margin:.4rem 0 0;", tx$example_note)
    )
  })

  # ── Step 2 ────────────────────────────────────────────────────────────────
  output$col_selector_panel <- renderUI({
    req(rv$df_raw)
    tx       <- t()
    all_cols <- colnames(rv$df_raw)
    # v1.1: al re-render (es. cambio lingua) mantiene la selezione dell'utente
    prev_sel   <- isolate(rv$sel_cols)
    active_set <- if (!is.null(prev_sel) && any(prev_sel %in% all_cols)) prev_sel else DEFAULT_KEEP
    n_active <- sum(all_cols %in% active_set)
    pills <- lapply(all_cols, function(col) {
      is_active <- col %in% active_set
      tags$span(class = paste("col-toggle", if (is_active) "active" else "excluded",
                              if (col %in% names(DERIVED_TRAITS)) "col-derived"),
                `data-col` = col, onclick = "toggleCol(this);", col)
    })
    div(class = "wr-card",
      p(class = "section-label", tx$step2),
      div(class = "toggle-actions",
        tags$button(class = "link-btn", onclick = "setAll(true)",  tx$sel_all),
        tags$button(class = "link-btn", onclick = "setAll(false)", tx$desel_all)
      ),
      div(class = "col-grid", pills),
      p(class = "toggle-meta", id = "col-meta",
        paste(n_active, tx$col_of, length(all_cols), tx$col_meta)),
      if (any(names(DERIVED_TRAITS) %in% all_cols))
        p(class = "toggle-meta", style = "margin-top:.5rem;", tx$derived_note)
    )
  })

  observe({
    req(rv$df_raw)
    active <- if (!is.null(input$active_col_count)) input$active_col_count
              else sum(colnames(rv$df_raw) %in% DEFAULT_KEEP)
    session$sendCustomMessage("updateColMeta",
      list(text = paste(active, t()$col_of, ncol(rv$df_raw), t()$col_meta)))
  })

  observeEvent(input$selected_cols, { rv$sel_cols <- input$selected_cols },
               ignoreNULL = FALSE)

  # ── Step 3 ────────────────────────────────────────────────────────────────
  output$step3_panel <- renderUI({
    req(rv$df_raw)
    tx  <- t()
    sep <- if (identical(isolate(input$csv_sep), "comma")) "comma" else "semicolon"
    sep_btn <- function(value, label) {
      tags$button(type = "button", class = paste("seg-btn", if (value == sep) "active"),
                  onclick = paste0("setCsvSep(this, '", value, "');"), label)
    }
    div(class = "wr-card",
      p(class = "section-label", tx$step3),
      div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap;",
        actionButton("clean_btn", tx$btn_clean, icon = icon("broom")),
        div(class = "dl-wrap", uiOutput("dl_ui"))
      ),
      div(class = "csv-sep-row",
        span(class = "csv-sep-lbl", tx$csv_sep_lbl),
        div(class = "seg-switch",
          sep_btn("semicolon", tx$csv_sep_semicolon),
          sep_btn("comma",     tx$csv_sep_comma)
        ),
        span(class = "csv-sep-hint", tx$csv_sep_hint)
      )
    )
  })

  observeEvent(input$clean_btn, {
    req(rv$df_raw)
    rv$df_clean <- rv$df_trt <- rv$df_final <- rv$error <- rv$chart_png_b64 <- NULL
    # "Deseleziona tutte": Shiny riceve l'array vuoto come NULL, quindi solo il
    # conteggio distingue questa scelta dalla selezione non ancora inizializzata.
    if (isTRUE(input$active_col_count == 0)) {
      rv$error <- t()$err_no_cols
      return()
    }
    tryCatch({
      df   <- rv$df_raw
      keep <- input$selected_cols
      if (is.null(keep) || !length(keep)) keep <- DEFAULT_KEEP
      keep_ord    <- colnames(df)[colnames(df) %in% keep]
      rv$df_clean <- apply_rename(df[, keep_ord, drop = FALSE])
    }, error = function(e) rv$error <- conditionMessage(e))
  })

  output$dl_ui <- renderUI({
    req(rv$df_clean)
    div(class = "dl-wrap", actionButton("dl_btn", t()$btn_dl_clean, icon = icon("download")))
  })

  observeEvent(input$dl_btn, {
    req(rv$df_clean)
    session$sendCustomMessage("downloadCSV", list(
      filename = paste0(rv$base_name, "_clean.csv"),
      content  = df_to_csv_string(rv$df_clean, sep = csv_sep())
    ))
  })

  # ── Anteprima step 3 ─────────────────────────────────────────────────────
  output$preview_panel <- renderUI({
    tx <- t()
    if (!is.null(rv$error) && is.null(rv$df_clean)) {
      div(class = "wr-card",
        div(style = "color:#991B1B; font-size:.9rem;", icon("circle-exclamation"), " ", rv$error))
    } else if (!is.null(rv$df_clean)) {
      df      <- rv$df_clean
      applied <- COL_RENAME[names(COL_RENAME) %in% colnames(rv$df_raw)]
      orig_id <- attr(rv$df_raw, "orig_id_col")
      if (!is.null(orig_id) && orig_id != "SampleId")
        applied <- c(setNames("SampleId", orig_id), applied)
      chips   <- lapply(names(applied), function(old)
        div(class = "rename-chip", span(old), span(class = "arr", "→"), span(class = "to", applied[[old]])))
      div(class = "wr-card",
        p(class = "section-label", tx$summary),
        if (length(chips)) tagList(
          p(style = "font-size:.88rem; color:#5A6B58; margin-bottom:.4rem;", tx$renamed_lbl),
          div(class = "rename-chips", chips),
          hr(class = "section-divider")
        ),
        div(class = "stats-strip",
          div(class="stat-item", span(class="stat-val", nrow(df)), span(class="stat-lbl", tx$stat_samples)),
          div(class="stat-item", span(class="stat-val", ncol(df)), span(class="stat-lbl", tx$stat_cols)),
          div(class="stat-item", span(class="stat-val", paste0(rv$base_name,"_clean.csv")), span(class="stat-lbl", tx$stat_file))
        ),
        p(class = "section-label", tx$preview8),
        div(class = "preview-wrap", tableOutput("preview_tbl"))
      )
    }
  })
  output$preview_tbl <- renderTable({ req(rv$df_clean); rv$df_clean },
    striped = FALSE, hover = TRUE, bordered = FALSE, spacing = "xs", na = "")

  # ── Step 4 ────────────────────────────────────────────────────────────────
  output$treatment_panel <- renderUI({
    req(rv$df_clean)
    tx       <- t()
    sid_col  <- if ("SampleId" %in% colnames(rv$df_clean)) "SampleId" else colnames(rv$df_clean)[1]
    samples  <- rv$df_clean[[sid_col]]
    up_n     <- isolate(rv$upload_n)

    n_levels <- scheme()

    manual_panel <- NULL
    manual_warning <- NULL

    if (n_levels == 3) {
      # ── Schema manuale: dropdown per ogni token del primo SampleId ────────
      ref_sample <- samples[1]
      sp <- split_sampleid_tokens(ref_sample)

      roles <- input$manual_roles
      if (is.null(roles) || length(roles) != length(sp$tokens)) {
        # default: tutto Treatment tranne l'ultimo (Plant)
        roles <- rep("Treatment", length(sp$tokens))
        if (length(roles) > 1) roles[length(roles)] <- "Plant"
      }

      seg_blocks <- list()
      for (j in seq_along(sp$tokens)) {
        sel_id <- paste0("segrole_", j)
        role_cls <- switch(roles[j],
          Treatment = "role-treatment", Pot = "role-pot",
          Plant = "role-plant", "")
        seg_blocks[[length(seg_blocks) + 1]] <- div(class = "segment-block",
          div(class = "segment-token", sp$tokens[j]),
          tags$select(id = sel_id, class = paste("segment-role-select", role_cls),
                      onchange = "updateSegmentRole(this);",
            tags$option(value = "Treatment", selected = if (roles[j] == "Treatment") "selected", tx$trt_manual_role_treatment),
            tags$option(value = "Pot",       selected = if (roles[j] == "Pot")       "selected", tx$trt_manual_role_pot),
            tags$option(value = "Plant",     selected = if (roles[j] == "Plant")     "selected", tx$trt_manual_role_plant),
            tags$option(value = "Ignore",    selected = if (roles[j] == "Ignore")    "selected", tx$trt_manual_role_ignore)
          )
        )
        if (j < length(sp$tokens)) {
          seg_blocks[[length(seg_blocks) + 1]] <- div(class = "segment-sep", sp$seps[j])
        }
      }

      manual_panel <- div(
        p(style = "font-size:.9rem; color:#5A6B58; margin-bottom:.4rem; font-weight:600;", tx$trt_manual_lbl),
        p(style = "font-size:.86rem; color:#9CA3AF; margin-bottom:.8rem;", tx$trt_manual_hint),
        div(class = "segment-row", seg_blocks)
      )

      result <- apply_manual_scheme(samples, roles)
      detected <- result$treatment
      rep1 <- result$pot
      rep2 <- result$plant
      rep1[is.na(rep1)] <- ""   # celle vuote in tabella
      rep2[is.na(rep2)] <- ""

      if (any(!result$ok)) {
        manual_warning <- div(class = "manual-warning",
          icon("triangle-exclamation"), " ", tx$trt_manual_mismatch)
      }

      tbl_header <- tags$thead(tags$tr(
        tags$th(tx$trt_col_sample), tags$th(tx$trt_col_detected),
        tags$th(tx$trt_col_vaso), tags$th(tx$trt_col_pianta), tags$th(tx$trt_col_custom)
      ))
      tbl_rows <- lapply(seq_along(samples), function(i) {
        sid    <- samples[i]; det <- detected[i]
        inp_id <- paste0("trt_", up_n, "_", i)
        tags$tr(
          tags$td(tags$code(sid)),
          tags$td(class = "trt-detected", det),
          tags$td(style = "text-align:center; font-weight:600; color:#5A6B58;", rep1[i]),
          tags$td(style = "text-align:center; font-weight:600; color:#5A6B58;", rep2[i]),
          tags$td(tags$input(type = "text", id = inp_id, class = "trt-input",
            value = isolate(input[[inp_id]]),
            placeholder = det,
            oninput = paste0("Shiny.setInputValue('", inp_id, "', this.value, {priority:'event'})")))
        )
      })

    } else {
      detected   <- extract_treatment(samples, n_levels)
      rep_levels <- extract_replicate_levels(samples, n_levels)

      if (anyNA(rep_levels[[1]])) {
        manual_warning <- div(class = "manual-warning",
          icon("triangle-exclamation"), " ", tx$trt_scheme_mismatch)
      }
      rep_levels <- lapply(rep_levels, function(x) { x[is.na(x)] <- ""; x })  # celle vuote in tabella

      if (n_levels == 1) {
        tbl_header <- tags$thead(tags$tr(
          tags$th(tx$trt_col_sample), tags$th(tx$trt_col_detected),
          tags$th(tx$trt_col_replica), tags$th(tx$trt_col_custom)
        ))
        tbl_rows <- lapply(seq_along(samples), function(i) {
          sid    <- samples[i]; det <- detected[i]
          inp_id <- paste0("trt_", up_n, "_", i)
          tags$tr(
            tags$td(tags$code(sid)),
            tags$td(class = "trt-detected", det),
            tags$td(style = "text-align:center; font-weight:600; color:#5A6B58;", rep_levels[[1]][i]),
            tags$td(tags$input(type = "text", id = inp_id, class = "trt-input",
            value = isolate(input[[inp_id]]),
              placeholder = det,
              oninput = paste0("Shiny.setInputValue('", inp_id, "', this.value, {priority:'event'})")))
          )
        })
      } else {
        tbl_header <- tags$thead(tags$tr(
          tags$th(tx$trt_col_sample), tags$th(tx$trt_col_detected),
          tags$th(tx$trt_col_vaso), tags$th(tx$trt_col_pianta), tags$th(tx$trt_col_custom)
        ))
        tbl_rows <- lapply(seq_along(samples), function(i) {
          sid    <- samples[i]; det <- detected[i]
          inp_id <- paste0("trt_", up_n, "_", i)
          tags$tr(
            tags$td(tags$code(sid)),
            tags$td(class = "trt-detected", det),
            tags$td(style = "text-align:center; font-weight:600; color:#5A6B58;", rep_levels[[1]][i]),
            tags$td(style = "text-align:center; font-weight:600; color:#5A6B58;", rep_levels[[2]][i]),
            tags$td(tags$input(type = "text", id = inp_id, class = "trt-input",
            value = isolate(input[[inp_id]]),
              placeholder = det,
              oninput = paste0("Shiny.setInputValue('", inp_id, "', this.value, {priority:'event'})")))
          )
        })
      }
    }

    div(class = "wr-card",
      p(class = "section-label", tx$step4),
      p(style = "font-size:.86rem; color:#5A6B58; margin-bottom:1rem;", tx$trt_hint),

      p(style = "font-size:.9rem; color:#5A6B58; margin-bottom:.5rem; font-weight:600;", tx$trt_scheme_lbl),
      div(class = "scheme-grid",
        div(class = paste("scheme-card", if (n_levels == 1) "active" else ""),
            onclick = "setScheme(this, 1);",
          div(class = "scheme-card-title", tx$trt_scheme_1),
          div(class = "scheme-card-sub",   tx$trt_scheme_1_sub)
        ),
        div(class = paste("scheme-card", if (n_levels == 2) "active" else ""),
            onclick = "setScheme(this, 2);",
          div(class = "scheme-card-title", tx$trt_scheme_2),
          div(class = "scheme-card-sub",   tx$trt_scheme_2_sub)
        ),
        div(class = paste("scheme-card", if (n_levels == 3) "active" else ""),
            onclick = "setScheme(this, 3);",
          div(class = "scheme-card-title", tx$trt_scheme_3),
          div(class = "scheme-card-sub",   tx$trt_scheme_3_sub)
        )
      ),

      manual_panel,
      manual_warning,

      div(style = "overflow-x:auto;",
        tags$table(class = "trt-table", tbl_header, tags$tbody(tbl_rows))
      ),
      hr(class = "section-divider"),
      div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap;",
        actionButton("trt_btn", tx$btn_trt, icon = icon("tags")),
        div(class = "dl-wrap", uiOutput("dl_trt_ui"))
      ),
      uiOutput("trt_preview_wrap")
    )
  })

  observeEvent(input$trt_btn, {
    req(rv$df_clean)
    rv$df_trt <- rv$df_final <- rv$error <- rv$chart_png_b64 <- NULL
    tryCatch({
      df       <- rv$df_clean
      sid_col  <- if ("SampleId" %in% colnames(df)) "SampleId" else colnames(df)[1]
      samples  <- df[[sid_col]]
      n_levels <- scheme()

      if (n_levels == 3) {
        ref_sample <- samples[1]
        sp    <- split_sampleid_tokens(ref_sample)
        roles <- input$manual_roles
        if (is.null(roles) || length(roles) != length(sp$tokens)) {
          roles <- rep("Treatment", length(sp$tokens))
          if (length(roles) > 1) roles[length(roles)] <- "Plant"
        }
        result   <- apply_manual_scheme(samples, roles)
        detected <- result$treatment
        rep1     <- result$pot
        rep2     <- result$plant
      } else {
        detected <- extract_treatment(samples, n_levels)
        rep_levels <- extract_replicate_levels(samples, n_levels)
        rep1 <- rep_levels[[1]]
        rep2 <- if (n_levels >= 2) rep_levels[[2]] else NULL
      }

      trt_vals <- vapply(seq_along(samples), function(i) {
        inp_id <- paste0("trt_", rv$upload_n, "_", i)
        val    <- input[[inp_id]]
        if (is.null(val) || trimws(val) == "") detected[i] else trimws(val)
      }, character(1))

      df$treatment <- trt_vals

      if (n_levels == 1) {
        df$replicate <- rep1
        new_cols     <- c("treatment", "replicate")
      } else {
        df$pot   <- rep1   # vaso / replica biologica
        df$plant <- rep2   # pianta / replica tecnica
        new_cols <- c("treatment", "pot", "plant")
      }

      sid_pos  <- which(colnames(df) == sid_col)
      rest     <- setdiff(colnames(df), c(colnames(df)[seq_len(sid_pos)], new_cols))
      rv$df_trt <- df[, c(colnames(df)[seq_len(sid_pos)], new_cols, rest), drop = FALSE]
    }, error = function(e) rv$error <- conditionMessage(e))
  })

  output$dl_trt_ui <- renderUI({
    req(rv$df_trt)
    div(class = "dl-wrap", actionButton("dl_trt_btn", t()$btn_dl_trt, icon = icon("download")))
  })

  observeEvent(input$dl_trt_btn, {
    req(rv$df_trt)
    session$sendCustomMessage("downloadCSV", list(
      filename = paste0(rv$base_name, "_treatments.csv"),
      content  = df_to_csv_string(rv$df_trt, sep = csv_sep())
    ))
  })

  output$trt_preview_wrap <- renderUI({
    req(rv$df_trt)
    tagList(
      hr(class = "section-divider"),
      p(class = "section-label", t()$trt_preview),
      div(class = "preview-wrap", tableOutput("trt_preview_tbl"))
    )
  })
  output$trt_preview_tbl <- renderTable({ req(rv$df_trt); rv$df_trt },
    striped = FALSE, hover = TRUE, bordered = FALSE, spacing = "xs", na = "")

  # ── Step 5: Controllo qualità ────────────────────────────────────────────
  # Le segnalazioni si calcolano su tutti i campioni, così l'elenco non cambia
  # mentre si escludono; le esclusioni valgono per i passaggi 6-8.
  kept_df <- reactive({
    req(rv$df_trt)
    ex <- rv$excluded[rv$excluded <= nrow(rv$df_trt)]
    out <- if (length(ex)) rv$df_trt[-ex, , drop = FALSE] else rv$df_trt
    rownames(out) <- NULL
    out
  })

  qc <- reactive({
    req(rv$df_trt)
    df <- rv$df_trt
    list(issues = qc_check(df, get_available_chart_params(df)), dups = qc_duplicates(df))
  })

  # Dopo ogni modifica il file finale e il grafico vanno rigenerati
  set_excluded <- function(rows) {
    rv$excluded <- sort(unique(as.integer(rows)))
    rv$df_final <- rv$chart_png_b64 <- NULL
  }

  observeEvent(input$qc_toggle, {
    r <- as.integer(input$qc_toggle$row)
    if (isTRUE(input$qc_toggle$include)) set_excluded(setdiff(rv$excluded, r))
    else set_excluded(c(rv$excluded, r))
  })
  observeEvent(input$qc_drop_dups, {
    set_excluded(c(rv$excluded, qc()$dups$older))
    rv$qc_version <- rv$qc_version + 1L
  })
  observeEvent(input$qc_reset, {
    set_excluded(integer())
    rv$qc_version <- rv$qc_version + 1L
  })

  output$qc_panel <- renderUI({
    req(rv$df_trt)
    rv$qc_version
    tx   <- t()
    df   <- rv$df_trt
    q    <- qc()
    excl <- isolate(rv$excluded)  # le caselle cambiano già nel browser
    sid  <- sample_id_col(df)
    flagged  <- sort(unique(q$issues$row))
    show_all <- isTRUE(input$qc_show_all)
    rows <- if (show_all) seq_len(nrow(df)) else sort(unique(c(flagged, excl)))
    issue_lbl <- c(duplicate = tx$qc_issue_duplicate, missing = tx$qc_issue_missing,
                   zero = tx$qc_issue_zero, outlier = tx$qc_issue_outlier)
    chips_for <- function(i) {
      iss <- q$issues[q$issues$row == i, , drop = FALSE]
      lapply(intersect(QC_ISSUES, iss$issue), function(type) {
        pars <- unique(iss$parameter[iss$issue == type & !is.na(iss$parameter)])
        span(class = paste0("qc-chip qc-chip-", type),
             paste0(issue_lbl[[type]], if (length(pars)) paste0(": ", paste(pars, collapse = ", "))))
      })
    }
    has_dt  <- "datetime" %in% colnames(df)
    has_src <- "source_file" %in% colnames(df)
    header <- tags$thead(tags$tr(
      tags$th(tx$qc_col_include), tags$th(tx$trt_col_sample), tags$th(tx$trt_manual_role_treatment),
      if (has_dt) tags$th("datetime"), if (has_src) tags$th("source_file"), tags$th(tx$qc_col_issues)
    ))
    body <- lapply(rows, function(i) {
      inc <- !(i %in% excl)
      tags$tr(class = if (!inc) "qc-excluded",
        tags$td(style = "text-align:center;",
          tags$input(type = "checkbox", class = "qc-include", `data-row` = i, checked = if (inc) NA,
                     `aria-label` = paste(tx$qc_col_include, df[[sid]][i]), onchange = "toggleQc(this);")),
        tags$td(tags$code(df[[sid]][i])),
        tags$td(class = "trt-detected", df$treatment[i]),
        if (has_dt)  tags$td(df$datetime[i]),
        if (has_src) tags$td(df$source_file[i]),
        tags$td(chips_for(i))
      )
    })

    div(class = "wr-card",
      p(class = "section-label", tx$step_qc),
      p(class = "chart-hint", tx$qc_hint),
      uiOutput("qc_stats"),
      if (!length(flagged)) p(class = "qc-ok", icon("circle-check"), " ", tx$qc_none),
      if (length(q$dups$older)) div(class = "qc-dups",
        actionButton("qc_drop_dups", tx$qc_drop_dups, icon = icon("clone")),
        span(class = "chart-hint", if (q$dups$by_time) tx$qc_dups_by_time else tx$qc_dups_by_order)
      ),
      div(id = "qc-show-all-toggle", class = paste("pivot-toggle", if (show_all) "on"),
          onclick = "toggleQcShowAll();",
        div(class = "pivot-switch"),
        div(div(class = "pivot-label", tx$qc_show_all_label),
            div(class = "pivot-sub",   tx$qc_show_all_sub))
      ),
      if (length(rows)) div(class = "preview-wrap", style = "margin-bottom:1rem;",
        tags$table(class = "trt-table qc-table", header, tags$tbody(body))),
      p(class = "chart-hint", tx$qc_regen_note),
      div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap;",
        div(class = "dl-wrap", actionButton("dl_qc_btn", tx$btn_dl_qc, icon = icon("download"))),
        uiOutput("qc_reset_ui")
      )
    )
  })

  # Conteggi e bilanciamento: seguono le esclusioni senza ridisegnare la tabella
  output$qc_stats <- renderUI({
    req(rv$df_trt)
    tx  <- t()
    q   <- qc()
    bal <- qc_balance(kept_df(), trt_order = input$trt_order)
    stat <- function(v, lbl) div(class = "stat-item", span(class = "stat-val", v), span(class = "stat-lbl", lbl))
    msg <- NULL
    if (!is.null(bal) && length(unique(bal$n)) > 1) {
      units <- if (has_pot_level(kept_df())) tx$qc_units_pot else tx$qc_units
      msg <- tagList(tags$strong(tx$qc_balance_lbl),
                     paste0(" (", units, "): ", paste(paste(bal$treatment, bal$n), collapse = " · "), "."))
    }
    if (!is.null(bal) && any(bal$n == 1)) msg <- tagList(msg, tx$qc_single)
    tagList(
      div(class = "stats-strip",
        stat(nrow(rv$df_trt), tx$stat_samples),
        stat(length(unique(q$issues$row)), tx$qc_stat_flagged),
        stat(length(rv$excluded), tx$qc_stat_excluded)
      ),
      if (!is.null(msg)) div(class = "manual-warning", icon("triangle-exclamation"), " ", msg)
    )
  })

  output$qc_reset_ui <- renderUI({
    req(length(rv$excluded) > 0)
    tags$button(class = "link-btn",
      onclick = "Shiny.setInputValue('qc_reset', Math.random(), {priority:'event'});",
      icon("rotate-left"), " ", t()$qc_reset)
  })

  observeEvent(input$dl_qc_btn, {
    req(rv$df_trt)
    session$sendCustomMessage("downloadCSV", list(
      filename = paste0(rv$base_name, "_qc.csv"),
      content  = df_to_csv_string(qc_report(rv$df_trt, qc()$issues, rv$excluded), sep = csv_sep())
    ))
  })

  # ── Step 6: Formato finale ───────────────────────────────────────────────
  output$pivot_panel <- renderUI({
    req(rv$df_trt)
    tx <- t()
    div(class = "wr-card",
      p(class = "section-label", tx$step_final),
      div(id = "pivot-toggle",
          class = paste("pivot-toggle", if (isTRUE(isolate(input$pivot_long))) "on"), onclick = "togglePivot();",
        div(class = "pivot-switch"),
        div(div(class = "pivot-label", tx$pivot_label),
            div(class = "pivot-sub",   tx$pivot_sub))
      ),
      div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap;",
        actionButton("pivot_btn", tx$btn_final, icon = icon("file-csv"),
          style = "border:none; color:#fff; font-weight:700; font-size:.95rem; padding:.58rem 1.6rem; border-radius:6px; background:#7C3AED;"),
        div(class = "dl-wrap", uiOutput("dl_final_ui"))
      ),
      uiOutput("final_preview_wrap")
    )
  })

  observeEvent(input$pivot_btn, {
    req(rv$df_trt)
    rv$df_final <- rv$error <- NULL
    df <- kept_df()
    if (!nrow(df)) {
      rv$error <- t()$qc_all_excluded
      return()
    }
    tryCatch({
      rv$df_final <- if (isTRUE(input$pivot_long)) pivot_long(df) else df
    }, error = function(e) rv$error <- conditionMessage(e))
  })

  output$dl_final_ui <- renderUI({
    req(rv$df_final)
    div(class = "dl-wrap", actionButton("dl_final_btn", t()$btn_dl_final, icon = icon("download")))
  })

  observeEvent(input$dl_final_btn, {
    req(rv$df_final)
    session$sendCustomMessage("downloadCSV", list(
      filename = paste0(rv$base_name, "_final.csv"),
      content  = df_to_csv_string(rv$df_final, sep = csv_sep())
    ))
  })

  output$final_preview_wrap <- renderUI({
    req(rv$df_final)
    tx <- t()
    tagList(
      hr(class = "section-divider"),
      div(class = "stats-strip",
        div(class="stat-item", span(class="stat-val", nrow(rv$df_final)), span(class="stat-lbl", tx$stat_rows)),
        div(class="stat-item", span(class="stat-val", ncol(rv$df_final)), span(class="stat-lbl", tx$stat_cols)),
        div(class="stat-item",
          span(class="stat-val", if ("parameter" %in% colnames(rv$df_final)) "long" else "wide"),
          span(class="stat-lbl", tx$stat_format)),
        if (length(rv$excluded)) div(class="stat-item",
          span(class="stat-val", length(rv$excluded)), span(class="stat-lbl", tx$stat_excluded)),
        div(class="stat-item",
          span(class="stat-val", paste0(rv$base_name, "_final.csv")),
          span(class="stat-lbl", tx$stat_file))
      ),
      p(class = "section-label", tx$final_preview),
      div(class = "preview-wrap", tableOutput("final_preview_tbl"))
    )
  })
  output$final_preview_tbl <- renderTable({ req(rv$df_final); rv$df_final },
    striped = FALSE, hover = TRUE, bordered = FALSE, spacing = "xs", na = "")

  # ── Step 7: Tabella riassuntiva ──────────────────────────────────────────
  # Dati wide dei campioni inclusi, come il grafico: non dipende dal formato finale.
  summary_df <- reactive({
    df <- kept_df()
    format_summary(summary_table(df, get_available_chart_params(df), trt_order = input$trt_order))
  })

  output$summary_panel <- renderUI({
    req(rv$df_final)
    if (!length(get_available_chart_params(kept_df()))) return(NULL)
    tx <- t()
    div(class = "wr-card",
      p(class = "section-label", tx$step_summary),
      p(class = "chart-hint", tx$summary_hint),
      if (has_pot_level(kept_df()))
        p(class = "chart-hint", style = "font-weight:600;", tx$summary_pot_note),
      div(class = "preview-wrap", style = "margin-bottom:1rem;", tableOutput("summary_tbl")),
      div(class = "dl-wrap", actionButton("dl_summary_btn", tx$btn_dl_summary, icon = icon("download")))
    )
  })
  output$summary_tbl <- renderTable(summary_df(), align = "llrrrr",
    striped = FALSE, hover = TRUE, bordered = FALSE, spacing = "xs", na = "")

  observeEvent(input$dl_summary_btn, {
    session$sendCustomMessage("downloadCSV", list(
      filename = paste0(rv$base_name, "_summary.csv"),
      content  = df_to_csv_string(summary_df(), sep = csv_sep())
    ))
  })

  # ── Step 8: Grafico esplorativo ──────────────────────────────────────────
  output$chart_panel <- renderUI({
    req(rv$df_final)
    tx <- t()

    if (!"treatment" %in% colnames(rv$df_final)) return(NULL)

    # parametri = colonne numeriche, escluse id/treatment/replicate
    avail_params <- get_available_chart_params(kept_df())

    if (!length(avail_params)) {
      return(div(class = "wr-card", p(class = "section-label", tx$step_chart),
                  p(style = "font-size:.92rem; color:#9CA3AF;", tx$chart_no_params)))
    }

    # v1.1: mantiene la selezione dei parametri ai re-render
    prev_par <- isolate(input$chart_params)
    act_par  <- if (!is.null(prev_par) && any(prev_par %in% avail_params)) prev_par else avail_params
    pills <- lapply(avail_params, function(p) {
      tags$span(class = paste("chart-param-toggle", if (p %in% act_par) "active" else "excluded"),
                `data-param` = p,
                onclick = "toggleChartParam(this);", p)
    })

    # Tipo di grafico, palette e ordine dei trattamenti restano ai re-render
    cur_type  <- isolate(input$chart_type)
    if (is.null(cur_type)) cur_type <- "bar"
    cur_pal   <- isolate(input$chart_palette)
    if (is.null(cur_pal)) cur_pal <- DEFAULT_PALETTE
    choice_card <- function(input_id, value, current, title, sub, extra = NULL) {
      tags$button(type = "button", class = paste("chart-type-card", if (value == current) "active"),
                  onclick = paste0("setChartChoice(this, '", input_id, "', '", value, "');"),
        div(class = "chart-type-title", title),
        div(class = "chart-type-sub", sub),
        extra
      )
    }
    type_card <- function(type, title, sub) choice_card("chart_type", type, cur_type, title, sub)
    pal_card  <- function(name, title, sub) {
      choice_card("chart_palette", name, cur_pal, title, sub,
        div(class = "palette-swatches", lapply(get_palette(name, 6), function(col) {
          span(class = "palette-swatch", style = paste0("background:", col, ";"))
        })))
    }
    trts <- order_treatments(kept_df()$treatment, isolate(input$trt_order))
    order_items <- lapply(trts, function(tr) {
      div(class = "trt-order-item", `data-trt` = tr,
        tags$button(type = "button", class = "trt-move trt-move-left", `aria-label` = tx$order_left,
                    onclick = "moveTrt(this, -1);", "\u25C0"),
        span(tr),
        tags$button(type = "button", class = "trt-move trt-move-right", `aria-label` = tx$order_right,
                    onclick = "moveTrt(this, 1);", "\u25B6")
      )
    })

    div(class = "wr-card",
      p(class = "section-label", tx$step_chart),
      p(class = "chart-hint", tx$chart_hint),
      if (has_pot_level(rv$df_final))
        p(class = "chart-hint", style = "font-weight:600;", tx$chart_pot_note),
      p(style = "font-size:.9rem; color:#5A6B58; margin-bottom:.5rem; font-weight:600;", tx$chart_param_lbl),
      div(class = "chart-param-grid", pills),
      p(style = "font-size:.9rem; color:#5A6B58; margin-bottom:.5rem; font-weight:600;", tx$chart_type_lbl),
      div(class = "chart-type-grid",
        type_card("bar",    tx$chart_type_bar,    tx$chart_type_bar_sub),
        type_card("box",    tx$chart_type_box,    tx$chart_type_box_sub),
        type_card("points", tx$chart_type_points, tx$chart_type_points_sub)
      ),
      p(style = "font-size:.9rem; color:#5A6B58; margin-bottom:.5rem; font-weight:600;", tx$palette_lbl),
      div(class = "chart-type-grid",
        pal_card("npg",   "NPG",          tx$palette_npg_sub),
        pal_card("okabe", "Okabe-Ito",    tx$palette_okabe_sub),
        pal_card("gray",  tx$palette_gray, tx$palette_gray_sub)
      ),
      if (length(trts) > 1) tagList(
        p(style = "font-size:.9rem; color:#5A6B58; margin-bottom:.5rem; font-weight:600;", tx$order_lbl),
        div(class = "trt-order-list", order_items),
        p(class = "chart-hint", tx$order_hint),
        div(id = "pct-toggle",
            class = paste("pivot-toggle", if (isTRUE(isolate(input$show_pct))) "on"), onclick = "togglePct();",
          div(class = "pivot-switch"),
          div(
            div(class = "pivot-label", tx$pct_label),
            div(class = "pivot-sub",   tx$pct_sub)
          )
        )
      ),
      # Il grafico a punti mostra già ogni replica
      conditionalPanel("input.chart_type !== 'points'",
        div(id = "jitter-toggle",
            class = paste("pivot-toggle", if (isTRUE(isolate(input$show_jitter))) "on"), onclick = "toggleJitter();",
          div(class = "pivot-switch"),
          div(
            div(class = "pivot-label", tx$jitter_label),
            div(class = "pivot-sub",   tx$jitter_sub)
          )
        )
      ),
      div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap;",
        actionButton("chart_btn", tx$btn_chart, icon = icon("chart-column")),
        uiOutput("dl_chart_ui"),
        uiOutput("clear_chart_ui")
      ),
      uiOutput("chart_render_wrap")
    )
  })

  observeEvent(input$chart_btn, {
    req(rv$df_final)
    rv$chart_png_b64 <- rv$error <- NULL

    avail_params <- get_available_chart_params(kept_df())
    sel_params   <- avail_params[avail_params %in% input$chart_params]
    if (!length(sel_params)) sel_params <- avail_params
    if (!length(sel_params)) return(NULL)

    # Il grafico usa sempre i dati wide dei campioni inclusi: riconvertire il formato
    # long con reshape() perderebbe i campioni con pot/plant/replicate vuoti.
    plot_df <- kept_df()
    spec <- list(
      df          = plot_df,
      params      = sel_params,
      type        = if (is.null(input$chart_type)) "bar" else input$chart_type,
      show_jitter = isTRUE(input$show_jitter),
      trt_order   = order_treatments(plot_df$treatment, input$trt_order),
      pct         = isTRUE(input$show_pct),
      palette     = if (is.null(input$chart_palette)) DEFAULT_PALETTE else input$chart_palette,
      labels      = chart_labels(t())
    )

    tmpfile <- tempfile(fileext = ".png")
    tryCatch({
      render_chart_file(spec, tmpfile, "png", t()$err_export)
      raw_bytes <- readBin(tmpfile, "raw", file.info(tmpfile)$size)
      rv$chart_png_b64 <- base64_encode_raw(raw_bytes)
      rv$chart_spec    <- spec
    }, error = function(e) rv$error <- conditionMessage(e),
       finally = unlink(tmpfile))
  })

  output$chart_render_wrap <- renderUI({
    req(rv$chart_png_b64)
    div(class = "chart-wrap",
      tags$img(src = paste0("data:image/png;base64,", rv$chart_png_b64))
    )
  })

  output$dl_chart_ui <- renderUI({
    req(rv$chart_png_b64)
    tx <- t()
    div(class = "dl-wrap", style = "display:flex; gap:.8rem; flex-wrap:wrap;",
      actionButton("dl_png_btn", tx$btn_dl_png, icon = icon("image")),
      actionButton("dl_pdf_btn", tx$btn_dl_pdf, icon = icon("file-pdf")),
      actionButton("dl_svg_btn", tx$btn_dl_svg, icon = icon("bezier-curve"))
    )
  })

  send_chart <- function(ext, mime, b64) {
    session$sendCustomMessage("downloadFile", list(
      filename = paste0(rv$base_name, "_chart.", ext),
      mime     = mime,
      data     = b64
    ))
  }

  # PDF e SVG riusano la specifica del grafico mostrato, anche se nel frattempo
  # sono cambiate le opzioni: il file scaricato è sempre la figura a schermo.
  export_chart <- function(ext, mime) {
    req(rv$chart_png_b64, rv$chart_spec)
    rv$error <- NULL
    f <- tempfile(fileext = paste0(".", ext))
    tryCatch({
      render_chart_file(rv$chart_spec, f, ext, t()$err_export)
      send_chart(ext, mime, base64_encode_raw(readBin(f, "raw", file.info(f)$size)))
    }, error = function(e) rv$error <- conditionMessage(e),
       finally = unlink(f))
  }

  observeEvent(input$dl_png_btn, {
    req(rv$chart_png_b64)
    send_chart("png", "image/png", rv$chart_png_b64)
  })
  observeEvent(input$dl_pdf_btn, export_chart("pdf", "application/pdf"))
  observeEvent(input$dl_svg_btn, export_chart("svg", "image/svg+xml"))

  output$clear_chart_ui <- renderUI({
    req(rv$chart_png_b64)
    tags$button(class = "link-btn", style = "color:#9CA3AF;",
      onclick = "Shiny.setInputValue('clear_chart', Math.random(), {priority:'event'});",
      icon("xmark"), " ", t()$btn_clear)
  })
  observeEvent(input$clear_chart, { rv$chart_png_b64 <- NULL })

  # ── Errori dei passaggi 4-8 (quelli precedenti sono in preview_panel) ───────
  output$error_panel <- renderUI({
    req(rv$error, rv$df_clean)
    div(class = "wr-card",
      div(style = "color:#991B1B; font-size:.9rem;", icon("circle-exclamation"), " ", rv$error))
  })

  # ── Badge stato ───────────────────────────────────────────────────────────
  observe({
    tx  <- t()
    cls <- if (!is.null(rv$error))         "badge-error"
           else if (!is.null(rv$df_final) ||
                    !is.null(rv$df_trt)   ||
                    !is.null(rv$df_clean) ||
                    !is.null(rv$df_raw))   "badge-ok"
           else                             "badge-idle"
    txt <- if (!is.null(rv$error))         tx$status_error
           else if (!is.null(rv$df_final)) tx$status_final
           else if (!is.null(rv$df_trt))   tx$status_trt
           else if (!is.null(rv$df_clean)) tx$status_clean
           else if (!is.null(rv$df_raw))   tx$status_loaded
           else                             tx$status_waiting
    session$sendCustomMessage("updateBadge", list(text = txt, cls = cls))
  })
}

shinyApp(ui, server)
 
Cookie Preferences